repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/pal/src/libunwind/src/ptrace/_UPT_internal.h
/* libunwind - a platform-independent unwind library Copyright (C) 2003, 2005 Hewlett-Packard Co Contributed by David Mosberger-Tang <[email protected]> This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef _UPT_internal_h #define _UPT_internal_h #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifdef HAVE_SYS_PTRACE_H #include <sys/ptrace.h> #endif #ifdef HAVE_SYS_PROCFS_H #include <sys/procfs.h> #endif #include <errno.h> #include <libunwind-ptrace.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> #include "libunwind_i.h" struct UPT_info { pid_t pid; /* the process-id of the child we're unwinding */ struct elf_dyn_info edi; }; extern const int _UPT_reg_offset[UNW_REG_LAST + 1]; #endif /* _UPT_internal_h */
/* libunwind - a platform-independent unwind library Copyright (C) 2003, 2005 Hewlett-Packard Co Contributed by David Mosberger-Tang <[email protected]> This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef _UPT_internal_h #define _UPT_internal_h #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifdef HAVE_SYS_PTRACE_H #include <sys/ptrace.h> #endif #ifdef HAVE_SYS_PROCFS_H #include <sys/procfs.h> #endif #include <errno.h> #include <libunwind-ptrace.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> #include "libunwind_i.h" struct UPT_info { pid_t pid; /* the process-id of the child we're unwinding */ struct elf_dyn_info edi; }; extern const int _UPT_reg_offset[UNW_REG_LAST + 1]; #endif /* _UPT_internal_h */
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/native/libs/System.Security.Cryptography.Native.Android/pal_signature.c
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "pal_signature.h" int32_t AndroidCryptoNative_SignWithSignatureObject(JNIEnv* env, jobject signatureObject, jobject privateKey, const uint8_t* dgst, int32_t dgstlen, uint8_t* sig, int32_t* siglen) { abort_if_invalid_pointer_argument (dgst); abort_if_invalid_pointer_argument (sig); abort_if_invalid_pointer_argument (signatureObject); abort_if_invalid_pointer_argument (privateKey); if (!siglen) { return FAIL; } (*env)->CallVoidMethod(env, signatureObject, g_SignatureInitSign, privateKey); ON_EXCEPTION_PRINT_AND_GOTO(error); jbyteArray digestArray = make_java_byte_array(env, dgstlen); (*env)->SetByteArrayRegion(env, digestArray, 0, dgstlen, (const jbyte*)dgst); (*env)->CallVoidMethod(env, signatureObject, g_SignatureUpdate, digestArray); ReleaseLRef(env, digestArray); ON_EXCEPTION_PRINT_AND_GOTO(error); jbyteArray sigResult = (*env)->CallObjectMethod(env, signatureObject, g_SignatureSign); ON_EXCEPTION_PRINT_AND_GOTO(error); jsize sigSize = (*env)->GetArrayLength(env, sigResult); *siglen = sigSize; (*env)->GetByteArrayRegion(env, sigResult, 0, sigSize, (jbyte*)sig); ReleaseLRef(env, sigResult); return SUCCESS; error: return FAIL; } int32_t AndroidCryptoNative_VerifyWithSignatureObject(JNIEnv* env, jobject signatureObject, jobject publicKey, const uint8_t* dgst, int32_t dgstlen, const uint8_t* sig, int32_t siglen) { abort_if_invalid_pointer_argument (dgst); abort_if_invalid_pointer_argument (sig); abort_if_invalid_pointer_argument (signatureObject); abort_if_invalid_pointer_argument (publicKey); (*env)->CallVoidMethod(env, signatureObject, g_SignatureInitVerify, publicKey); ON_EXCEPTION_PRINT_AND_GOTO(error); jbyteArray digestArray = make_java_byte_array(env, dgstlen); (*env)->SetByteArrayRegion(env, digestArray, 0, dgstlen, (const jbyte*)dgst); (*env)->CallVoidMethod(env, signatureObject, g_SignatureUpdate, digestArray); ReleaseLRef(env, digestArray); ON_EXCEPTION_PRINT_AND_GOTO(error); jbyteArray sigArray = make_java_byte_array(env, siglen); (*env)->SetByteArrayRegion(env, sigArray, 0, siglen, (const jbyte*)sig); jboolean verified = (*env)->CallBooleanMethod(env, signatureObject, g_SignatureVerify, sigArray); ReleaseLRef(env, sigArray); ON_EXCEPTION_PRINT_AND_GOTO(verifyFail); return verified ? SUCCESS : FAIL; error: return SIGNATURE_VERIFICATION_ERROR; verifyFail: return FAIL; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "pal_signature.h" int32_t AndroidCryptoNative_SignWithSignatureObject(JNIEnv* env, jobject signatureObject, jobject privateKey, const uint8_t* dgst, int32_t dgstlen, uint8_t* sig, int32_t* siglen) { abort_if_invalid_pointer_argument (dgst); abort_if_invalid_pointer_argument (sig); abort_if_invalid_pointer_argument (signatureObject); abort_if_invalid_pointer_argument (privateKey); if (!siglen) { return FAIL; } (*env)->CallVoidMethod(env, signatureObject, g_SignatureInitSign, privateKey); ON_EXCEPTION_PRINT_AND_GOTO(error); jbyteArray digestArray = make_java_byte_array(env, dgstlen); (*env)->SetByteArrayRegion(env, digestArray, 0, dgstlen, (const jbyte*)dgst); (*env)->CallVoidMethod(env, signatureObject, g_SignatureUpdate, digestArray); ReleaseLRef(env, digestArray); ON_EXCEPTION_PRINT_AND_GOTO(error); jbyteArray sigResult = (*env)->CallObjectMethod(env, signatureObject, g_SignatureSign); ON_EXCEPTION_PRINT_AND_GOTO(error); jsize sigSize = (*env)->GetArrayLength(env, sigResult); *siglen = sigSize; (*env)->GetByteArrayRegion(env, sigResult, 0, sigSize, (jbyte*)sig); ReleaseLRef(env, sigResult); return SUCCESS; error: return FAIL; } int32_t AndroidCryptoNative_VerifyWithSignatureObject(JNIEnv* env, jobject signatureObject, jobject publicKey, const uint8_t* dgst, int32_t dgstlen, const uint8_t* sig, int32_t siglen) { abort_if_invalid_pointer_argument (dgst); abort_if_invalid_pointer_argument (sig); abort_if_invalid_pointer_argument (signatureObject); abort_if_invalid_pointer_argument (publicKey); (*env)->CallVoidMethod(env, signatureObject, g_SignatureInitVerify, publicKey); ON_EXCEPTION_PRINT_AND_GOTO(error); jbyteArray digestArray = make_java_byte_array(env, dgstlen); (*env)->SetByteArrayRegion(env, digestArray, 0, dgstlen, (const jbyte*)dgst); (*env)->CallVoidMethod(env, signatureObject, g_SignatureUpdate, digestArray); ReleaseLRef(env, digestArray); ON_EXCEPTION_PRINT_AND_GOTO(error); jbyteArray sigArray = make_java_byte_array(env, siglen); (*env)->SetByteArrayRegion(env, sigArray, 0, siglen, (const jbyte*)sig); jboolean verified = (*env)->CallBooleanMethod(env, signatureObject, g_SignatureVerify, sigArray); ReleaseLRef(env, sigArray); ON_EXCEPTION_PRINT_AND_GOTO(verifyFail); return verified ? SUCCESS : FAIL; error: return SIGNATURE_VERIFICATION_ERROR; verifyFail: return FAIL; }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/native/public/mono/metadata/mono-config.h
/** * \file * * Author: Paolo Molaro ([email protected]) * * (C) 2002 Ximian, Inc. */ #ifndef __MONO_METADATA_CONFIG_H__ #define __MONO_METADATA_CONFIG_H__ #include <mono/metadata/details/mono-config-types.h> MONO_BEGIN_DECLS #define MONO_API_FUNCTION(ret,name,args) MONO_API ret name args; #include <mono/metadata/details/mono-config-functions.h> #undef MONO_API_FUNCTION MONO_END_DECLS #endif /* __MONO_METADATA_CONFIG_H__ */
/** * \file * * Author: Paolo Molaro ([email protected]) * * (C) 2002 Ximian, Inc. */ #ifndef __MONO_METADATA_CONFIG_H__ #define __MONO_METADATA_CONFIG_H__ #include <mono/metadata/details/mono-config-types.h> MONO_BEGIN_DECLS #define MONO_API_FUNCTION(ret,name,args) MONO_API ret name args; #include <mono/metadata/details/mono-config-functions.h> #undef MONO_API_FUNCTION MONO_END_DECLS #endif /* __MONO_METADATA_CONFIG_H__ */
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/vm/interoplibinterface.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // Interface between the VM and Interop library. // #ifndef _INTEROPLIBINTERFACE_H_ #define _INTEROPLIBINTERFACE_H_ #ifdef FEATURE_COMWRAPPERS namespace InteropLibInterface { // Base definition of the external object context. struct ExternalObjectContextBase { PTR_VOID Identity; DWORD SyncBlockIndex; }; } // Native calls for the managed ComWrappers API class ComWrappersNative { public: static const INT64 InvalidWrapperId = 0; public: // Lifetime management for COM Wrappers static void DestroyManagedObjectComWrapper(_In_ void* wrapper); static void DestroyExternalComObjectContext(_In_ void* context); static void MarkExternalComObjectContextCollected(_In_ void* context); public: // COM activation static void MarkWrapperAsComActivated(_In_ IUnknown* wrapperMaybe); public: // Unwrapping support static IUnknown* GetIdentityForObject(_In_ OBJECTREF* objectPROTECTED, _In_ REFIID riid, _Out_ INT64* wrapperId, _Out_ bool* isAggregated); static bool HasManagedObjectComWrapper(_In_ OBJECTREF object, _Out_ bool* isActive); public: // GC interaction static void OnFullGCStarted(); static void OnFullGCFinished(); static void AfterRefCountedHandleCallbacks(); }; // Native QCalls for the abstract ComWrappers managed type. extern "C" void QCALLTYPE ComWrappers_GetIUnknownImpl( _Out_ void** fpQueryInterface, _Out_ void** fpAddRef, _Out_ void** fpRelease); extern "C" BOOL QCALLTYPE ComWrappers_TryGetOrCreateComInterfaceForObject( _In_ QCall::ObjectHandleOnStack comWrappersImpl, _In_ INT64 wrapperId, _In_ QCall::ObjectHandleOnStack instance, _In_ INT32 flags, _Outptr_ void** wrapperRaw); extern "C" BOOL QCALLTYPE ComWrappers_TryGetOrCreateObjectForComInstance( _In_ QCall::ObjectHandleOnStack comWrappersImpl, _In_ INT64 wrapperId, _In_ void* externalComObject, _In_opt_ void* innerMaybe, _In_ INT32 flags, _In_ QCall::ObjectHandleOnStack wrapperMaybe, _Inout_ QCall::ObjectHandleOnStack retValue); // Native QCall for the ComWrappers managed type to indicate a global instance // is registered for marshalling. This should be set if the private static member // representing the global instance for marshalling on ComWrappers is non-null. extern "C" void QCALLTYPE ComWrappers_SetGlobalInstanceRegisteredForMarshalling(_In_ INT64 id); // Native QCall for the ComWrappers managed type to indicate a global instance // is registered for tracker support. This should be set if the private static member // representing the global instance for tracker support on ComWrappers is non-null. extern "C" void QCALLTYPE ComWrappers_SetGlobalInstanceRegisteredForTrackerSupport(_In_ INT64 id); class GlobalComWrappersForMarshalling { public: // Functions operating on a registered global instance for marshalling static bool IsRegisteredInstance(_In_ INT64 id); static bool TryGetOrCreateComInterfaceForObject( _In_ OBJECTREF instance, _Outptr_ void** wrapperRaw); static bool TryGetOrCreateObjectForComInstance( _In_ IUnknown* externalComObject, _In_ INT32 objFromComIPFlags, _Out_ OBJECTREF* objRef); }; class GlobalComWrappersForTrackerSupport { public: // Functions operating on a registered global instance for tracker support static bool IsRegisteredInstance(_In_ INT64 id); static bool TryGetOrCreateComInterfaceForObject( _In_ OBJECTREF instance, _Outptr_ void** wrapperRaw); static bool TryGetOrCreateObjectForComInstance( _In_ IUnknown* externalComObject, _Out_ OBJECTREF* objRef); }; #endif // FEATURE_COMWRAPPERS #ifdef FEATURE_OBJCMARSHAL class ObjCMarshalNative { public: using BeginEndCallback = void(STDMETHODCALLTYPE *)(void); using IsReferencedCallback = int(STDMETHODCALLTYPE *)(_In_ void*); using EnteredFinalizationCallback = void(STDMETHODCALLTYPE *)(_In_ void*); // See MessageSendFunction in ObjectiveCMarshal class enum MessageSendFunction { MessageSendFunction_MsgSend = 0, MessageSendFunction_MsgSendFpret = 1, MessageSendFunction_MsgSendStret = 2, MessageSendFunction_MsgSendSuper = 3, MessageSendFunction_MsgSendSuperStret = 4, Last = MessageSendFunction_MsgSendSuperStret, }; public: // Instance inspection static bool IsTrackedReference(_In_ OBJECTREF object, _Out_ bool* isReferenced); public: // Identification static bool IsRuntimeMessageSendFunction( _In_z_ const char* libraryName, _In_z_ const char* entrypointName); public: // Exceptions static void* GetPropagatingExceptionCallback( _In_ EECodeInfo* codeInfo, _In_ OBJECTHANDLE throwable, _Outptr_ void** context); public: // GC interaction static void BeforeRefCountedHandleCallbacks(); static void AfterRefCountedHandleCallbacks(); static void OnEnteredFinalizerQueue(_In_ OBJECTREF object); }; extern "C" BOOL QCALLTYPE ObjCMarshal_TryInitializeReferenceTracker( _In_ ObjCMarshalNative::BeginEndCallback beginEndCallback, _In_ ObjCMarshalNative::IsReferencedCallback isReferencedCallback, _In_ ObjCMarshalNative::EnteredFinalizationCallback trackedObjectEnteredFinalization); extern "C" void* QCALLTYPE ObjCMarshal_CreateReferenceTrackingHandle( _In_ QCall::ObjectHandleOnStack obj, _Out_ int* memInSizeT, _Outptr_ void** mem); extern "C" BOOL QCALLTYPE ObjCMarshal_TrySetGlobalMessageSendCallback( _In_ ObjCMarshalNative::MessageSendFunction msgSendFunction, _In_ void* fptr); #endif // FEATURE_OBJCMARSHAL class Interop { public: // Check if pending exceptions are possible for the following native export. static bool ShouldCheckForPendingException(_In_ NDirectMethodDesc* md); // A no return callback that is designed to help propagate a managed // exception going from Managed to Native. using ManagedToNativeExceptionCallback = /* no return */ void(*)(_In_ void* context); static ManagedToNativeExceptionCallback GetPropagatingExceptionCallback( _In_ EECodeInfo* codeInfo, _In_ OBJECTHANDLE throwable, _Outptr_ void** context); // Notify started/finished when GC is running. // These methods are called in a blocking fashion when a // GC of generation is started. These calls may overlap // so care must be taken when taking locks. static void OnGCStarted(_In_ int nCondemnedGeneration); static void OnGCFinished(_In_ int nCondemnedGeneration); // Notify before/after when GC is scanning roots. // Present assumption is that calls will never be nested. // The input indicates if the call is from a concurrent GC // thread or not. These will be nested within OnGCStarted // and OnGCFinished. static void OnBeforeGCScanRoots(_In_ bool isConcurrent); static void OnAfterGCScanRoots(_In_ bool isConcurrent); }; #endif // _INTEROPLIBINTERFACE_H_
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // Interface between the VM and Interop library. // #ifndef _INTEROPLIBINTERFACE_H_ #define _INTEROPLIBINTERFACE_H_ #ifdef FEATURE_COMWRAPPERS namespace InteropLibInterface { // Base definition of the external object context. struct ExternalObjectContextBase { PTR_VOID Identity; DWORD SyncBlockIndex; }; } // Native calls for the managed ComWrappers API class ComWrappersNative { public: static const INT64 InvalidWrapperId = 0; public: // Lifetime management for COM Wrappers static void DestroyManagedObjectComWrapper(_In_ void* wrapper); static void DestroyExternalComObjectContext(_In_ void* context); static void MarkExternalComObjectContextCollected(_In_ void* context); public: // COM activation static void MarkWrapperAsComActivated(_In_ IUnknown* wrapperMaybe); public: // Unwrapping support static IUnknown* GetIdentityForObject(_In_ OBJECTREF* objectPROTECTED, _In_ REFIID riid, _Out_ INT64* wrapperId, _Out_ bool* isAggregated); static bool HasManagedObjectComWrapper(_In_ OBJECTREF object, _Out_ bool* isActive); public: // GC interaction static void OnFullGCStarted(); static void OnFullGCFinished(); static void AfterRefCountedHandleCallbacks(); }; // Native QCalls for the abstract ComWrappers managed type. extern "C" void QCALLTYPE ComWrappers_GetIUnknownImpl( _Out_ void** fpQueryInterface, _Out_ void** fpAddRef, _Out_ void** fpRelease); extern "C" BOOL QCALLTYPE ComWrappers_TryGetOrCreateComInterfaceForObject( _In_ QCall::ObjectHandleOnStack comWrappersImpl, _In_ INT64 wrapperId, _In_ QCall::ObjectHandleOnStack instance, _In_ INT32 flags, _Outptr_ void** wrapperRaw); extern "C" BOOL QCALLTYPE ComWrappers_TryGetOrCreateObjectForComInstance( _In_ QCall::ObjectHandleOnStack comWrappersImpl, _In_ INT64 wrapperId, _In_ void* externalComObject, _In_opt_ void* innerMaybe, _In_ INT32 flags, _In_ QCall::ObjectHandleOnStack wrapperMaybe, _Inout_ QCall::ObjectHandleOnStack retValue); // Native QCall for the ComWrappers managed type to indicate a global instance // is registered for marshalling. This should be set if the private static member // representing the global instance for marshalling on ComWrappers is non-null. extern "C" void QCALLTYPE ComWrappers_SetGlobalInstanceRegisteredForMarshalling(_In_ INT64 id); // Native QCall for the ComWrappers managed type to indicate a global instance // is registered for tracker support. This should be set if the private static member // representing the global instance for tracker support on ComWrappers is non-null. extern "C" void QCALLTYPE ComWrappers_SetGlobalInstanceRegisteredForTrackerSupport(_In_ INT64 id); class GlobalComWrappersForMarshalling { public: // Functions operating on a registered global instance for marshalling static bool IsRegisteredInstance(_In_ INT64 id); static bool TryGetOrCreateComInterfaceForObject( _In_ OBJECTREF instance, _Outptr_ void** wrapperRaw); static bool TryGetOrCreateObjectForComInstance( _In_ IUnknown* externalComObject, _In_ INT32 objFromComIPFlags, _Out_ OBJECTREF* objRef); }; class GlobalComWrappersForTrackerSupport { public: // Functions operating on a registered global instance for tracker support static bool IsRegisteredInstance(_In_ INT64 id); static bool TryGetOrCreateComInterfaceForObject( _In_ OBJECTREF instance, _Outptr_ void** wrapperRaw); static bool TryGetOrCreateObjectForComInstance( _In_ IUnknown* externalComObject, _Out_ OBJECTREF* objRef); }; #endif // FEATURE_COMWRAPPERS #ifdef FEATURE_OBJCMARSHAL class ObjCMarshalNative { public: using BeginEndCallback = void(STDMETHODCALLTYPE *)(void); using IsReferencedCallback = int(STDMETHODCALLTYPE *)(_In_ void*); using EnteredFinalizationCallback = void(STDMETHODCALLTYPE *)(_In_ void*); // See MessageSendFunction in ObjectiveCMarshal class enum MessageSendFunction { MessageSendFunction_MsgSend = 0, MessageSendFunction_MsgSendFpret = 1, MessageSendFunction_MsgSendStret = 2, MessageSendFunction_MsgSendSuper = 3, MessageSendFunction_MsgSendSuperStret = 4, Last = MessageSendFunction_MsgSendSuperStret, }; public: // Instance inspection static bool IsTrackedReference(_In_ OBJECTREF object, _Out_ bool* isReferenced); public: // Identification static bool IsRuntimeMessageSendFunction( _In_z_ const char* libraryName, _In_z_ const char* entrypointName); public: // Exceptions static void* GetPropagatingExceptionCallback( _In_ EECodeInfo* codeInfo, _In_ OBJECTHANDLE throwable, _Outptr_ void** context); public: // GC interaction static void BeforeRefCountedHandleCallbacks(); static void AfterRefCountedHandleCallbacks(); static void OnEnteredFinalizerQueue(_In_ OBJECTREF object); }; extern "C" BOOL QCALLTYPE ObjCMarshal_TryInitializeReferenceTracker( _In_ ObjCMarshalNative::BeginEndCallback beginEndCallback, _In_ ObjCMarshalNative::IsReferencedCallback isReferencedCallback, _In_ ObjCMarshalNative::EnteredFinalizationCallback trackedObjectEnteredFinalization); extern "C" void* QCALLTYPE ObjCMarshal_CreateReferenceTrackingHandle( _In_ QCall::ObjectHandleOnStack obj, _Out_ int* memInSizeT, _Outptr_ void** mem); extern "C" BOOL QCALLTYPE ObjCMarshal_TrySetGlobalMessageSendCallback( _In_ ObjCMarshalNative::MessageSendFunction msgSendFunction, _In_ void* fptr); #endif // FEATURE_OBJCMARSHAL class Interop { public: // Check if pending exceptions are possible for the following native export. static bool ShouldCheckForPendingException(_In_ NDirectMethodDesc* md); // A no return callback that is designed to help propagate a managed // exception going from Managed to Native. using ManagedToNativeExceptionCallback = /* no return */ void(*)(_In_ void* context); static ManagedToNativeExceptionCallback GetPropagatingExceptionCallback( _In_ EECodeInfo* codeInfo, _In_ OBJECTHANDLE throwable, _Outptr_ void** context); // Notify started/finished when GC is running. // These methods are called in a blocking fashion when a // GC of generation is started. These calls may overlap // so care must be taken when taking locks. static void OnGCStarted(_In_ int nCondemnedGeneration); static void OnGCFinished(_In_ int nCondemnedGeneration); // Notify before/after when GC is scanning roots. // Present assumption is that calls will never be nested. // The input indicates if the call is from a concurrent GC // thread or not. These will be nested within OnGCStarted // and OnGCFinished. static void OnBeforeGCScanRoots(_In_ bool isConcurrent); static void OnAfterGCScanRoots(_In_ bool isConcurrent); }; #endif // _INTEROPLIBINTERFACE_H_
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/vm/interpreter.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #ifndef INTERPRETER_H_DEFINED #define INTERPRETER_H_DEFINED 1 #include "corjit.h" #include "corinfo.h" #include "codeman.h" #include "jitinterface.h" #include "stack.h" #include "crst.h" #include "callhelpers.h" #include "codeversion.h" #include "clr_std/type_traits" typedef SSIZE_T NativeInt; typedef SIZE_T NativeUInt; typedef SIZE_T NativePtr; // Determines whether we interpret IL stubs. (We might disable this selectively for // some architectures, perhaps.) #define INTERP_ILSTUBS 1 // If this is set, we keep track of extra information about IL instructions executed per-method. #define INTERP_PROFILE 0 // If this is set, we track the distribution of IL instructions. #define INTERP_ILINSTR_PROFILE 0 #define INTERP_ILCYCLE_PROFILE 0 #if INTERP_ILCYCLE_PROFILE #if !INTERP_ILINSTR_PROFILE #error INTERP_ILCYCLE_PROFILE may only be set if INTERP_ILINSTR_PROFILE is also set. #endif #endif #if defined(_DEBUG) || INTERP_ILINSTR_PROFILE // I define "INTERP_TRACING", rather than just using _DEBUG, so that I can easily make a build // in which tracing is enabled in retail. #define INTERP_TRACING 1 #else #define INTERP_TRACING 0 #endif // defined(_DEBUG) || defined(INTERP_ILINSTR_PROFILE) #if INTERP_TRACING #define INTERPLOG(...) if (s_TraceInterpreterVerboseFlag.val(CLRConfig::INTERNAL_TraceInterpreterVerbose)) { fprintf(GetLogFile(), __VA_ARGS__); } #else #define INTERPLOG(...) #endif #if INTERP_TRACING #define InterpTracingArg(x) ,x #else #define InterpTracingArg(x) #endif #define FEATURE_INTERPRETER_DEADSIMPLE_OPT 0 #define NYI_INTERP(msg) _ASSERTE_MSG(false, msg) // I wanted to define NYI_INTERP as the following in retail: // #define NYI_INTERP(msg) _ASSERTE_ALL_BUILDS(__FILE__, false) // but doing so gave a very odd unreachable code error. // To allow keeping a pointer (index) to the vararg cookie argument to implement arglist. // Use sentinel value of NO_VA_ARGNUM. #define NO_VA_ARGNUM UINT_MAX // First, a set of utility routines on CorInfoTypes. // Returns "true" iff "cit" is "stack-normal": all integer types with byte size less than 4 // are folded to CORINFO_TYPE_INT; all remaining unsigned types are folded to their signed counterparts. bool IsStackNormalType(CorInfoType cit); // Returns the stack-normal CorInfoType that contains "cit". CorInfoType CorInfoTypeStackNormalize(CorInfoType cit); // Returns the (byte) size of "cit". Requires that "cit" is not a CORINFO_TYPE_VALUECLASS. size_t CorInfoTypeSize(CorInfoType cit); // Returns true iff "cit" is an unsigned integral type. bool CorInfoTypeIsUnsigned(CorInfoType cit); // Returns true iff "cit" is an integral type. bool CorInfoTypeIsIntegral(CorInfoType cit); // Returns true iff "cet" is an unsigned integral type. bool CorElemTypeIsUnsigned(CorElementType cet); // Returns true iff "cit" is a floating-point type. bool CorInfoTypeIsFloatingPoint(CorInfoType cit); // Returns true iff "cihet" is a floating-point type (float or double). // TODO: Handle Vector64, Vector128? bool CorInfoTypeIsFloatingPoint(CorInfoHFAElemType cihet); // Returns true iff "cit" is a pointer type (mgd/unmgd pointer, or native int). bool CorInfoTypeIsPointer(CorInfoType cit); // Requires that "cit" is stack-normal; returns its (byte) size. inline size_t CorInfoTypeStackNormalSize(CorInfoType cit) { _ASSERTE(IsStackNormalType(cit)); return CorInfoTypeSize(cit); } inline unsigned getClassSize(CORINFO_CLASS_HANDLE clsHnd) { TypeHandle VMClsHnd(clsHnd); return VMClsHnd.GetSize(); } // The values of this enumeration are in one-to-one correspondence with CorInfoType -- // just shifted so that they're the value stored in an interpreter type for non-value-class // CorinfoTypes. enum CorInfoTypeShifted { CORINFO_TYPE_SHIFTED_UNDEF = unsigned(CORINFO_TYPE_UNDEF) << 2, //0x0 << 2 = 0x0 CORINFO_TYPE_SHIFTED_VOID = unsigned(CORINFO_TYPE_VOID) << 2, //0x1 << 2 = 0x4 CORINFO_TYPE_SHIFTED_BOOL = unsigned(CORINFO_TYPE_BOOL) << 2, //0x2 << 2 = 0x8 CORINFO_TYPE_SHIFTED_CHAR = unsigned(CORINFO_TYPE_CHAR) << 2, //0x3 << 2 = 0xC CORINFO_TYPE_SHIFTED_BYTE = unsigned(CORINFO_TYPE_BYTE) << 2, //0x4 << 2 = 0x10 CORINFO_TYPE_SHIFTED_UBYTE = unsigned(CORINFO_TYPE_UBYTE) << 2, //0x5 << 2 = 0x14 CORINFO_TYPE_SHIFTED_SHORT = unsigned(CORINFO_TYPE_SHORT) << 2, //0x6 << 2 = 0x18 CORINFO_TYPE_SHIFTED_USHORT = unsigned(CORINFO_TYPE_USHORT) << 2, //0x7 << 2 = 0x1C CORINFO_TYPE_SHIFTED_INT = unsigned(CORINFO_TYPE_INT) << 2, //0x8 << 2 = 0x20 CORINFO_TYPE_SHIFTED_UINT = unsigned(CORINFO_TYPE_UINT) << 2, //0x9 << 2 = 0x24 CORINFO_TYPE_SHIFTED_LONG = unsigned(CORINFO_TYPE_LONG) << 2, //0xa << 2 = 0x28 CORINFO_TYPE_SHIFTED_ULONG = unsigned(CORINFO_TYPE_ULONG) << 2, //0xb << 2 = 0x2C CORINFO_TYPE_SHIFTED_NATIVEINT = unsigned(CORINFO_TYPE_NATIVEINT) << 2, //0xc << 2 = 0x30 CORINFO_TYPE_SHIFTED_NATIVEUINT = unsigned(CORINFO_TYPE_NATIVEUINT) << 2, //0xd << 2 = 0x34 CORINFO_TYPE_SHIFTED_FLOAT = unsigned(CORINFO_TYPE_FLOAT) << 2, //0xe << 2 = 0x38 CORINFO_TYPE_SHIFTED_DOUBLE = unsigned(CORINFO_TYPE_DOUBLE) << 2, //0xf << 2 = 0x3C CORINFO_TYPE_SHIFTED_STRING = unsigned(CORINFO_TYPE_STRING) << 2, //0x10 << 2 = 0x40 CORINFO_TYPE_SHIFTED_PTR = unsigned(CORINFO_TYPE_PTR) << 2, //0x11 << 2 = 0x44 CORINFO_TYPE_SHIFTED_BYREF = unsigned(CORINFO_TYPE_BYREF) << 2, //0x12 << 2 = 0x48 CORINFO_TYPE_SHIFTED_VALUECLASS = unsigned(CORINFO_TYPE_VALUECLASS) << 2, //0x13 << 2 = 0x4C CORINFO_TYPE_SHIFTED_CLASS = unsigned(CORINFO_TYPE_CLASS) << 2, //0x14 << 2 = 0x50 CORINFO_TYPE_SHIFTED_REFANY = unsigned(CORINFO_TYPE_REFANY) << 2, //0x15 << 2 = 0x54 CORINFO_TYPE_SHIFTED_VAR = unsigned(CORINFO_TYPE_VAR) << 2, //0x16 << 2 = 0x58 }; class InterpreterType { // We use this typedef, but the InterpreterType is actually encoded. We assume that the two // low-order bits of a "real" CORINFO_CLASS_HANDLE are zero, then use them as follows: // 0x0 ==> if "ci" is a non-struct CORINFO_TYPE_* value, m_tp contents are (ci << 2). // 0x1, 0x3 ==> is a CORINFO_CLASS_HANDLE "sh" for a struct type, or'd with 0x1 and possibly 0x2. // 0x2 is added to indicate that an instance does not fit in a INT64 stack slot on the plaform, and // should be referenced via a level of indirection. // 0x2 (exactly) indicates that it is a "native struct type". // CORINFO_CLASS_HANDLE m_tp; public: // Default ==> undefined. InterpreterType() : m_tp(reinterpret_cast<CORINFO_CLASS_HANDLE>((static_cast<intptr_t>(CORINFO_TYPE_UNDEF) << 2))) {} // Requires that "cit" is not CORINFO_TYPE_VALUECLASS. InterpreterType(CorInfoType cit) : m_tp(reinterpret_cast<CORINFO_CLASS_HANDLE>((static_cast<intptr_t>(cit) << 2))) { _ASSERTE(cit != CORINFO_TYPE_VALUECLASS); } // Requires that "cet" is not ELEMENT_TYPE_VALUETYPE. InterpreterType(CorElementType cet) : m_tp(reinterpret_cast<CORINFO_CLASS_HANDLE>((static_cast<intptr_t>(CEEInfo::asCorInfoType(cet)) << 2))) { _ASSERTE(cet != ELEMENT_TYPE_VALUETYPE); } InterpreterType(CEEInfo* comp, CORINFO_CLASS_HANDLE sh) { GCX_PREEMP(); // TODO: might wish to make a different constructor, for the cases where this is possible... TypeHandle typHnd(sh); if (typHnd.IsNativeValueType()) { intptr_t shAsInt = reinterpret_cast<intptr_t>(sh); _ASSERTE((shAsInt & 0x1) == 0); // The 0x2 bit might already be set by the VM! This is ok, because it's only set for native value types. This is a bit slimey... m_tp = reinterpret_cast<CORINFO_CLASS_HANDLE>(shAsInt | 0x2); } else { CorInfoType cit = comp->getTypeForPrimitiveValueClass(sh); if (cit != CORINFO_TYPE_UNDEF) { m_tp = reinterpret_cast<CORINFO_CLASS_HANDLE>(static_cast<intptr_t>(cit) << 2); } else { _ASSERTE((comp->getClassAttribs(sh) & CORINFO_FLG_VALUECLASS) != 0); intptr_t shAsInt = reinterpret_cast<intptr_t>(sh); _ASSERTE((shAsInt & 0x3) == 0); intptr_t bits = 0x1; // All value classes (structs) get 0x1 set. if (getClassSize(sh) > sizeof(INT64)) { bits |= 0x2; // "Large" structs get 0x2 set, also. } m_tp = reinterpret_cast<CORINFO_CLASS_HANDLE>(shAsInt | bits); } } } bool operator==(const InterpreterType& it2) const { return m_tp == it2.m_tp; } bool operator!=(const InterpreterType& it2) const { return m_tp != it2.m_tp; } CorInfoType ToCorInfoType() const { LIMITED_METHOD_CONTRACT; intptr_t iTypeAsInt = reinterpret_cast<intptr_t>(m_tp); if ((iTypeAsInt & 0x3) == 0x0) { return static_cast<CorInfoType>(iTypeAsInt >> 2); } // Is a class or struct (or refany?). else { return CORINFO_TYPE_VALUECLASS; } } CorInfoType ToCorInfoTypeNotStruct() const { LIMITED_METHOD_CONTRACT; _ASSERTE_MSG((reinterpret_cast<intptr_t>(m_tp) & 0x3) == 0x0, "precondition: not a struct type."); intptr_t iTypeAsInt = reinterpret_cast<intptr_t>(m_tp); return static_cast<CorInfoType>(iTypeAsInt >> 2); } CorInfoTypeShifted ToCorInfoTypeShifted() const { LIMITED_METHOD_CONTRACT; _ASSERTE_MSG((reinterpret_cast<intptr_t>(m_tp) & 0x3) == 0x0, "precondition: not a struct type."); return static_cast<CorInfoTypeShifted>(reinterpret_cast<size_t>(m_tp)); } CORINFO_CLASS_HANDLE ToClassHandle() const { LIMITED_METHOD_CONTRACT; intptr_t asInt = reinterpret_cast<intptr_t>(m_tp); _ASSERTE((asInt & 0x3) != 0); return reinterpret_cast<CORINFO_CLASS_HANDLE>(asInt & (~0x3)); } size_t AsRaw() const // Just hand out the raw bits. Be careful using this! Use something else if you can! { LIMITED_METHOD_CONTRACT; return reinterpret_cast<size_t>(m_tp); } // Returns the stack-normalized type for "this". InterpreterType StackNormalize() const; // Returns the (byte) size of "this". Requires "ceeInfo" for the struct case. __forceinline size_t Size(CEEInfo* ceeInfo) const { LIMITED_METHOD_CONTRACT; intptr_t asInt = reinterpret_cast<intptr_t>(m_tp); intptr_t asIntBits = (asInt & 0x3); if (asIntBits == 0) { return CorInfoTypeSize(ToCorInfoType()); } else if (asIntBits == 0x2) { // Here we're breaking abstraction, and taking advantage of the fact that 0x2 // is the low-bit encoding of "native struct type" both for InterpreterType and for // TypeHandle. TypeHandle typHnd(m_tp); _ASSERTE(typHnd.IsNativeValueType()); return typHnd.AsNativeValueType()->GetNativeSize(); } else { return getClassSize(ToClassHandle()); } } __forceinline size_t SizeNotStruct() const { LIMITED_METHOD_CONTRACT; _ASSERTE_MSG((reinterpret_cast<intptr_t>(m_tp) & 0x3) == 0, "Precondition: is not a struct type!"); return CorInfoTypeSize(ToCorInfoTypeNotStruct()); } // Requires that "it" is stack-normal; returns its (byte) size. size_t StackNormalSize() const { CorInfoType cit = ToCorInfoType(); _ASSERTE(IsStackNormalType(cit)); // Precondition. return CorInfoTypeStackNormalSize(cit); } // Is it a struct? (But don't include "native struct type"). bool IsStruct() const { intptr_t asInt = reinterpret_cast<intptr_t>(m_tp); return (asInt & 0x1) == 0x1 || (asInt == CORINFO_TYPE_SHIFTED_REFANY); } // Returns "true" iff represents a large (> INT64 size) struct. bool IsLargeStruct(CEEInfo* ceeInfo) const { intptr_t asInt = reinterpret_cast<intptr_t>(m_tp); #if defined(TARGET_AMD64) && !defined(UNIX_AMD64_ABI) if (asInt == CORINFO_TYPE_SHIFTED_REFANY) { return true; } #endif return (asInt & 0x3) == 0x3 || ((asInt & 0x3) == 0x2 && Size(ceeInfo) > sizeof(INT64)); } #ifdef _DEBUG bool MatchesWork(const InterpreterType it2, CEEInfo* info) const; bool Matches(const InterpreterType it2, CEEInfo* info) const { CONTRACTL { THROWS; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; return MatchesWork(it2, info) || it2.MatchesWork(*this, info); } #endif // _DEBUG }; #ifndef DACCESS_COMPILE // This class does whatever "global" (applicable to all executions after the first, as opposed to caching // within a single execution) we do. It is parameterized over the "Key" type (which is required to be an integral // type, to allow binary search), and the "Val" type of things cached. template<typename Key, typename Val> class InterpreterCache { public: InterpreterCache(); // Returns "false" if "k" is already present, otherwise "true". Requires that "v" == current mapping // if "k" is already present. bool AddItem(Key k, Val v); bool GetItem(Key k, Val& v); private: struct KeyValPair { Key m_key; Val m_val; }; // This is kept ordered by m_iloffset, to enable binary search. KeyValPair* m_pairs; unsigned short m_allocSize; unsigned short m_count; static const unsigned InitSize = 8; void EnsureCanInsert(); #ifdef _DEBUG static void AddAllocBytes(unsigned bytes); #endif // _DEBUG }; #ifdef _DEBUG enum CachedItemKind { CIK_Undefined, CIK_CallSite, CIK_StaticField, CIK_InstanceField, CIK_ClassHandle, }; #endif // _DEBUG struct StaticFieldCacheEntry { void* m_srcPtr; UINT m_sz; InterpreterType m_it; StaticFieldCacheEntry(void* srcPtr, UINT sz, InterpreterType it) : m_srcPtr(srcPtr), m_sz(sz), m_it(it) {} #ifdef _DEBUG bool operator==(const StaticFieldCacheEntry& entry) const { return m_srcPtr == entry.m_srcPtr && m_sz == entry.m_sz && m_it == entry.m_it; } #endif // _DEBUG }; // "small" part of CORINFO_SIG_INFO, sufficient for the interpreter to call the method so decribed struct CORINFO_SIG_INFO_SMALL { CORINFO_CLASS_HANDLE retTypeClass; // if the return type is a value class, this is its handle (enums are normalized) unsigned numArgs : 16; CorInfoCallConv callConv: 8; CorInfoType retType : 8; CorInfoCallConv getCallConv() { return CorInfoCallConv((callConv & CORINFO_CALLCONV_MASK)); } bool hasThis() { return ((callConv & CORINFO_CALLCONV_HASTHIS) != 0); } bool hasExplicitThis() { return ((callConv & CORINFO_CALLCONV_EXPLICITTHIS) != 0); } unsigned totalILArgs() { return (numArgs + hasThis()); } bool isVarArg() { return ((getCallConv() == CORINFO_CALLCONV_VARARG) || (getCallConv() == CORINFO_CALLCONV_NATIVEVARARG)); } bool hasTypeArg() { return ((callConv & CORINFO_CALLCONV_PARAMTYPE) != 0); } #ifdef _DEBUG bool operator==(const CORINFO_SIG_INFO_SMALL& csis) const { return retTypeClass == csis.retTypeClass && numArgs == csis.numArgs && callConv == csis.callConv && retType == csis.retType; } #endif // _DEBUG }; struct CallSiteCacheData { MethodDesc* m_pMD; CORINFO_SIG_INFO_SMALL m_sigInfo; CallSiteCacheData(MethodDesc* pMD, const CORINFO_SIG_INFO_SMALL& sigInfo) : m_pMD(pMD), m_sigInfo(sigInfo) {} #ifdef _DEBUG bool operator==(const CallSiteCacheData& cscd) const { return m_pMD == cscd.m_pMD && m_sigInfo == cscd.m_sigInfo; } #endif // _DEBUG }; struct CachedItem { #ifdef _DEBUG CachedItemKind m_tag; #endif // _DEBUG union { // m_tag == CIK_CallSite CallSiteCacheData* m_callSiteInfo; // m_tag == CIK_StaticField StaticFieldCacheEntry* m_staticFieldAddr; // m_tag == CIK_InstanceField FieldDesc* m_instanceField; // m_tag == CIT_ClassHandle CORINFO_CLASS_HANDLE m_clsHnd; } m_value; CachedItem() #ifdef _DEBUG : m_tag(CIK_Undefined) #endif {} #ifdef _DEBUG bool operator==(const CachedItem& ci) { if (m_tag != ci.m_tag) return false; switch (m_tag) { case CIK_CallSite: return *m_value.m_callSiteInfo == *ci.m_value.m_callSiteInfo; case CIK_StaticField: return *m_value.m_staticFieldAddr == *ci.m_value.m_staticFieldAddr; case CIK_InstanceField: return m_value.m_instanceField == ci.m_value.m_instanceField; case CIK_ClassHandle: return m_value.m_clsHnd == ci.m_value.m_clsHnd; default: return true; } } #endif CachedItem(CallSiteCacheData* callSiteInfo) #ifdef _DEBUG : m_tag(CIK_CallSite) #endif { m_value.m_callSiteInfo = callSiteInfo; } CachedItem(StaticFieldCacheEntry* staticFieldAddr) #ifdef _DEBUG : m_tag(CIK_StaticField) #endif { m_value.m_staticFieldAddr = staticFieldAddr; } CachedItem(FieldDesc* instanceField) #ifdef _DEBUG : m_tag(CIK_InstanceField) #endif { m_value.m_instanceField = instanceField; } CachedItem(CORINFO_CLASS_HANDLE m_clsHnd) #ifdef _DEBUG : m_tag(CIK_ClassHandle) #endif { m_value.m_clsHnd = m_clsHnd; } }; const char* eeGetMethodFullName(CEEInfo* info, CORINFO_METHOD_HANDLE hnd, const char** clsName = NULL); // The per-InterpMethodInfo cache may map generic instantiation information to the // cache for the current instantitation; when we find the right one the first time we copy it // into here, so we only have to do the instantiation->cache lookup once. typedef InterpreterCache<unsigned, CachedItem> ILOffsetToItemCache; typedef InterpreterCache<size_t, ILOffsetToItemCache*> GenericContextToInnerCache; #endif // DACCESS_COMPILE // This is the information that the intepreter stub provides to the // interpreter about the method being interpreted. struct InterpreterMethodInfo { #if INTERP_PROFILE || defined(_DEBUG) const char* m_clsName; const char* m_methName; #endif // Stub num for the current method under interpretation. int m_stubNum; // The method this info is relevant to. CORINFO_METHOD_HANDLE m_method; // The module containing the method. CORINFO_MODULE_HANDLE m_module; // Code pointer, size, and max stack usage. BYTE* m_ILCode; BYTE* m_ILCodeEnd; // One byte past the last byte of IL. IL Code Size = m_ILCodeEnd - m_ILCode. // The CLR transforms delegate constructors, and may add up to this many // extra arguments. This amount will be added to the IL's reported MaxStack to // get the "maxStack" value below, so we can use a uniform calling convention for // "DoCall". unsigned m_maxStack; unsigned m_ehClauseCount; // Used to implement arglist, an index into the ilArgs array where the argument pointed to is VA sig cookie. unsigned m_varArgHandleArgNum; // The number of arguments. unsigned short m_numArgs; // The number of local variables. unsigned short m_numLocals; enum Flags { // Is the first argument a "this" pointer? Flag_hasThisArg, // If "m_hasThisArg" is true, indicates whether the type of this is an object pointer // or a byref. Flag_thisArgIsObjPtr, // Is there a return buffer argument? Flag_hasRetBuffArg, // Is the method a var arg method Flag_isVarArg, // Is the last argument a generic type context? Flag_hasGenericsContextArg, // Does the type have generic args? Flag_typeHasGenericArgs, // Does the method have generic args? Flag_methHasGenericArgs, // Is the method a "dead simple" getter (one that just reads a field?) Flag_methIsDeadSimpleGetter, // We recognize two forms of dead simple getters, one for "opt" and one for "dbg". If it is // dead simple, is it dbg or opt? Flag_methIsDeadSimpleGetterIsDbgForm, Flag_Count, }; typedef UINT16 FlagGroup; // The bitmask for a set of InterpreterMethodInfo::Flags. FlagGroup m_flags; template<int Flg> FlagGroup GetFlagBit() { // This works as long as FlagGroup is "int" type. static_assert(sizeof(FlagGroup) * 8 >= Flag_Count, "error: bitset not large enough"); return (1 << Flg); } // Get and set the value of a flag. template<int Flg> bool GetFlag() { return (m_flags & GetFlagBit<Flg>()) != 0; } template<int Flg> void SetFlag(bool b) { if (b) m_flags |= GetFlagBit<Flg>(); else m_flags &= (~GetFlagBit<Flg>()); } // This structure describes a local: its type and its offset. struct LocalDesc { InterpreterType m_typeStackNormal; InterpreterType m_type; unsigned m_offset; }; // This structure describes an argument. Much like a LocalDesc, but // "m_nativeOffset" contains the offset if the argument was passed using the system's native calling convention // (e.g., the calling convention for a JIT -> Interpreter call) whereas "m_directOffset" describes arguments passed // via a direct Interpreter -> Interpreter call. struct ArgDesc { InterpreterType m_typeStackNormal; InterpreterType m_type; short m_nativeOffset; short m_directOffset; }; // This is an array of size at least "m_numArgs", such that entry "i" describes the "i'th" // arg in the "m_ilArgs" array passed to the intepreter: that is, the ArgDesc contains the type, stack-normal type, // and offset in the "m_ilArgs" array of that argument. In addition, has extra entries if "m_hasGenericsContextArg" // and/or "m_hasRetBuffArg" are true, giving the offset of those arguments -- the offsets of those arguments // are in that order in the array. (The corresponding types should be NativeInt.) ArgDesc* m_argDescs; // This is an array of size "m_numLocals", such that entry "i" describes the "i'th" // local : that is, the LocalDesc contains the type, stack-normal type, and, if the type // is a large struct type, the offset in the local variable large-struct memory array. LocalDesc* m_localDescs; // A bit map, with 1 bit per local, indicating whether it contains a pinning reference. char* m_localIsPinningRefBits; unsigned m_largeStructLocalSize; unsigned LocalMemSize() { return m_largeStructLocalSize + m_numLocals * sizeof(INT64); } // I will probably need more information about the return value, but for now... CorInfoType m_returnType; // The number of times this method has been interpreted. unsigned int m_invocations; #if INTERP_PROFILE UINT64 m_totIlInstructionsExeced; unsigned m_maxIlInstructionsExeced; void RecordExecInstrs(unsigned instrs) { m_totIlInstructionsExeced += instrs; if (instrs > m_maxIlInstructionsExeced) { m_maxIlInstructionsExeced = instrs; } } #endif // #ifndef DACCESS_COMPILE // Caching information. Currently the only thing we cache is saved formats of MethodDescCallSites // at call instructions. // We use a "void*", because the actual type depends on the whether the method has // a dynamic generics context. If so, this is a cache from the generic parameter to an // ILoffset->item cache; if not, it's a the ILoffset->item cache directly. void* m_methodCache; // #endif // DACCESS_COMPILE InterpreterMethodInfo(CEEInfo* comp, CORINFO_METHOD_INFO* methInfo); void InitArgInfo(CEEInfo* comp, CORINFO_METHOD_INFO* methInfo, short* argOffsets_); void AllocPinningBitsIfNeeded(); void SetPinningBit(unsigned locNum); bool GetPinningBit(unsigned locNum); CORINFO_CONTEXT_HANDLE GetPreciseGenericsContext(Object* thisArg, void* genericsCtxtArg); #ifndef DACCESS_COMPILE // Gets the proper cache for a call to a method with the current InterpreterMethodInfo, with the given // "thisArg" and "genericsCtxtArg". If "alloc" is true, will allocate the cache if necessary. ILOffsetToItemCache* GetCacheForCall(Object* thisArg, void* genericsCtxtArg, bool alloc = false); #endif // DACCESS_COMPILE ~InterpreterMethodInfo(); }; // Expose some protected methods of CEEInfo. class InterpreterCEEInfo: public CEEInfo { CEEJitInfo m_jitInfo; public: InterpreterCEEInfo(CORINFO_METHOD_HANDLE meth): CEEInfo((MethodDesc*)meth), m_jitInfo((MethodDesc*)meth, NULL, NULL, CORJIT_FLAGS::CORJIT_FLAG_SPEED_OPT) { } // Certain methods are unimplemented by CEEInfo (they hit an assert). They are implemented by CEEJitInfo, yet // don't seem to require any of the CEEJitInfo state we can't provide. For those case, delegate to the "partial" // CEEJitInfo m_jitInfo. void addActiveDependency(CORINFO_MODULE_HANDLE moduleFrom,CORINFO_MODULE_HANDLE moduleTo) { m_jitInfo.addActiveDependency(moduleFrom, moduleTo); } }; extern INT64 F_CALL_CONV InterpretMethod(InterpreterMethodInfo* methInfo, BYTE* ilArgs, void* stubContext); extern float F_CALL_CONV InterpretMethodFloat(InterpreterMethodInfo* methInfo, BYTE* ilArgs, void* stubContext); extern double F_CALL_CONV InterpretMethodDouble(InterpreterMethodInfo* methInfo, BYTE* ilArgs, void* stubContext); class Interpreter { friend INT64 F_CALL_CONV InterpretMethod(InterpreterMethodInfo* methInfo, BYTE* ilArgs, void* stubContext); friend float F_CALL_CONV InterpretMethodFloat(InterpreterMethodInfo* methInfo, BYTE* ilArgs, void* stubContext); friend double F_CALL_CONV InterpretMethodDouble(InterpreterMethodInfo* methInfo, BYTE* ilArgs, void* stubContext); // This will be inlined into the bodies of the methods above static inline ARG_SLOT InterpretMethodBody(InterpreterMethodInfo* interpMethInfo, bool directCall, BYTE* ilArgs, void* stubContext); // The local frame size of the method being interpreted. static size_t GetFrameSize(InterpreterMethodInfo* interpMethInfo); // JIT the method if we've passed the threshold, or if "force" is true. static void JitMethodIfAppropriate(InterpreterMethodInfo* interpMethInfo, bool force = false); friend class InterpreterFrame; public: // Return an interpreter stub for the given method. That is, a stub that transforms the arguments from the native // calling convention to the interpreter convention, and provides the method descriptor, then calls the interpreter. // If "jmpCall" setting is true, then "ppInterpreterMethodInfo" must be provided and the GenerateInterpreterStub // will NOT generate a stub. Instead it will provide a MethodInfo that is initialized correctly after computing // arg descs. static CorJitResult GenerateInterpreterStub(CEEInfo* comp, CORINFO_METHOD_INFO* info, /*OUT*/ BYTE **nativeEntry, /*OUT*/ ULONG *nativeSizeOfCode, InterpreterMethodInfo** ppInterpMethodInfo = NULL, bool jmpCall = false); // If "addr" is the start address of an interpreter stub, return the corresponding MethodDesc*, // else "NULL". static class MethodDesc* InterpretationStubToMethodInfo(PCODE addr); // A value to indicate that the cache has not been initialized (to distinguish it from NULL -- // we've looked and it doesn't yet have a cache.) #define UninitExecCache reinterpret_cast<ILOffsetToItemCache*>(0x1) // The "frameMemory" should be a pointer to a locally-allocated memory block // whose size is sufficient to hold the m_localVarMemory, the operand stack, and the // operand type stack. Interpreter(InterpreterMethodInfo* methInfo_, bool directCall_, BYTE* ilArgs_, void* stubContext_, BYTE* frameMemory) : m_methInfo(methInfo_), m_interpCeeInfo(methInfo_->m_method), m_ILCodePtr(methInfo_->m_ILCode), m_directCall(directCall_), m_ilArgs(ilArgs_), m_stubContext(stubContext_), m_orOfPushedInterpreterTypes(0), m_largeStructOperandStack(NULL), m_largeStructOperandStackHt(0), m_largeStructOperandStackAllocSize(0), m_curStackHt(0), m_leaveInfoStack(), m_filterNextScan(0), m_filterHandlerOffset(0), m_filterExcILOffset(0), m_inFlightException(NULL), m_thisArg(NULL), #ifdef USE_CHECKED_OBJECTREFS m_retBufArg(NULL), // Initialize to NULL so we can safely declare protected. #endif // USE_CHECKED_OBJECTREFS m_genericsCtxtArg(NULL), m_securityObject((Object*)NULL), m_args(NULL), m_argsSize(0), m_callThisArg(NULL), m_structRetValITPtr(NULL), #ifndef DACCESS_COMPILE // Means "uninitialized" m_thisExecCache(UninitExecCache), #endif m_constrainedFlag(false), m_readonlyFlag(false), m_locAllocData(NULL), m_preciseGenericsContext(NULL), m_functionPointerStack(NULL) { // We must zero the locals. memset(frameMemory, 0, methInfo_->LocalMemSize() + sizeof(GSCookie)); // m_localVarMemory is below the fixed size slots, above the large struct slots. m_localVarMemory = frameMemory + methInfo_->m_largeStructLocalSize + sizeof(GSCookie); m_gsCookieAddr = (GSCookie*) (m_localVarMemory - sizeof(GSCookie)); // Having zeroed, for large struct locals, we must initialize the fixed-size local slot to point to the // corresponding large-struct local slot. for (unsigned i = 0; i < methInfo_->m_numLocals; i++) { if (methInfo_->m_localDescs[i].m_type.IsLargeStruct(&m_interpCeeInfo)) { void* structPtr = ArgSlotEndianessFixup(reinterpret_cast<ARG_SLOT*>(FixedSizeLocalSlot(i)), sizeof(void**)); *reinterpret_cast<void**>(structPtr) = LargeStructLocalSlot(i); } } frameMemory += methInfo_->LocalMemSize(); frameMemory += sizeof(GSCookie); #define COMBINE_OPSTACK_VAL_TYPE 0 #if COMBINE_OPSTACK_VAL_TYPE m_operandStackX = reinterpret_cast<OpStackValAndType*>(frameMemory); frameMemory += (methInfo_->m_maxStack * sizeof(OpStackValAndType)); #else m_operandStack = reinterpret_cast<INT64*>(frameMemory); frameMemory += (methInfo_->m_maxStack * sizeof(INT64)); m_operandStackTypes = reinterpret_cast<InterpreterType*>(frameMemory); #endif // If we have a "this" arg, save it in case we need it later. (So we can // reliably get it even if the IL updates arg 0...) if (m_methInfo->GetFlag<InterpreterMethodInfo::Flag_hasThisArg>()) { m_thisArg = *reinterpret_cast<Object**>(GetArgAddr(0)); } unsigned extraArgInd = methInfo_->m_numArgs - 1; // We do these in the *reverse* of the order they appear in the array, so that we can conditionally process // the ones that are used. if (m_methInfo->GetFlag<InterpreterMethodInfo::Flag_hasGenericsContextArg>()) { m_genericsCtxtArg = *reinterpret_cast<Object**>(GetArgAddr(extraArgInd)); extraArgInd--; } if (m_methInfo->GetFlag<InterpreterMethodInfo::Flag_isVarArg>()) { extraArgInd--; } if (m_methInfo->GetFlag<InterpreterMethodInfo::Flag_hasRetBuffArg>()) { m_retBufArg = *reinterpret_cast<void**>(GetArgAddr(extraArgInd)); extraArgInd--; } } ~Interpreter() { if (m_largeStructOperandStack != NULL) { delete[] m_largeStructOperandStack; } if (m_locAllocData != NULL) { delete m_locAllocData; } if (m_functionPointerStack != NULL) { delete[] m_functionPointerStack; } } // Called during EE startup to initialize locks and other generic resources. static void Initialize(); // Called during stub generation to initialize compiler-specific resources. static void InitializeCompilerStatics(CEEInfo* info); // Called during EE shutdown to destroy locks and release generic resources. static void Terminate(); // Returns true iff "stackPtr" can only be in younger frames than "this". (On a downwards- // growing stack, it is less than the smallest local address of "this".) bool IsInCalleesFrames(void* stackPtr); MethodDesc* GetMethodDesc() { return reinterpret_cast<MethodDesc*>(m_methInfo->m_method); } #if INTERP_ILSTUBS void* GetStubContext() { return m_stubContext; } #endif OBJECTREF* GetAddressOfSecurityObject() { return &m_securityObject; } void* GetParamTypeArg() { return m_genericsCtxtArg; } private: // Architecture-dependent helpers. inline static unsigned short NumberOfIntegerRegArgs(); // Wrapper for ExecuteMethod to do a O(1) alloca when performing a jmpCall and normal calls. If doJmpCall is true, this method also resolves the call token into pResolvedToken. static ARG_SLOT ExecuteMethodWrapper(struct InterpreterMethodInfo* interpMethInfo, bool directCall, BYTE* ilArgs, void* stubContext, bool* pDoJmpCall, CORINFO_RESOLVED_TOKEN* pResolvedCallToken); // Execute the current method, and set *retVal to the return value, if any. void ExecuteMethod(ARG_SLOT* retVal, bool* pDoJmpCall, unsigned* pJumpCallToken); // Fetches the monitor for static methods by asking cee info. Returns the monitor // object. AwareLock* GetMonitorForStaticMethod(); // Synchronized methods have to call monitor enter and exit at the entry and exits of the // method. void DoMonitorEnterWork(); void DoMonitorExitWork(); // Determines if the current exception is handled by the current method. If so, // returns true and sets the interpreter state to start executing in the appropriate handler. bool MethodHandlesException(OBJECTREF orThrowable); // Assumes that "ilCode" is the first instruction in a method, whose code is of size "codeSize". // Returns "false" if this method has no loops; if it returns "true", it might have a loop. static bool MethodMayHaveLoop(BYTE* ilCode, unsigned codeSize); // Do anything that needs to be done on a backwards branch (e.g., GC poll). // Assumes that "offset" is the delta between the current code pointer and the post-branch pointer; // obviously, it will be negative. void BackwardsBranchActions(int offset); // Expects "interp0" to be the address of the interpreter object being scanned. static void GCScanRoots(promote_func* pf, ScanContext* sc, void* interp0); // The above calls this instance method. void GCScanRoots(promote_func* pf, ScanContext* sc); // Scan the root at "loc", whose type is "it", using "pf" and "sc". void GCScanRootAtLoc(Object** loc, InterpreterType it, promote_func* pf, ScanContext* sc, bool pinningRef = false); // Scan the root at "loc", whose type is the value class "valueCls", using "pf" and "sc". void GCScanValueClassRootAtLoc(Object** loc, CORINFO_CLASS_HANDLE valueClsHnd, promote_func* pf, ScanContext* sc); // Asserts that "addr" is the start of the interpretation stub for "md". Records this in a table, // to satisfy later calls to "InterpretationStubToMethodInfo." static void RecordInterpreterStubForMethodDesc(CORINFO_METHOD_HANDLE md, void* addr); struct ArgState { unsigned short numRegArgs; unsigned short numFPRegArgSlots; unsigned fpArgsUsed; // Bit per single-precision fp arg accounted for. short callerArgStackSlots; short* argOffsets; enum ArgRegStatus { ARS_IntReg, ARS_FloatReg, ARS_NotReg }; ArgRegStatus* argIsReg; ArgState(unsigned totalArgs) : numRegArgs(0), numFPRegArgSlots(0), fpArgsUsed(0), callerArgStackSlots(0), argOffsets(new short[totalArgs]), argIsReg(new ArgRegStatus[totalArgs]) { for (unsigned i = 0; i < totalArgs; i++) { argIsReg[i] = ARS_NotReg; argOffsets[i] = 0; } } #if defined(HOST_ARM) static const int MaxNumFPRegArgSlots = 16; #elif defined(HOST_ARM64) static const int MaxNumFPRegArgSlots = 8; #elif defined(HOST_AMD64) #if defined(UNIX_AMD64_ABI) static const int MaxNumFPRegArgSlots = 8; #else static const int MaxNumFPRegArgSlots = 4; #endif #endif ~ArgState() { delete[] argOffsets; delete[] argIsReg; } void AddArg(unsigned canonIndex, short numSlots = 1, bool noReg = false, bool twoSlotAlign = false); // By this call, argument "canonIndex" is declared to be a floating point argument, taking the given # // of slots. Important that this be called in argument order. void AddFPArg(unsigned canonIndex, unsigned short numSlots, bool doubleAlign); #if defined(HOST_AMD64) // We have a special function for AMD64 because both integer/float registers overlap. However, all // callers are expected to call AddArg/AddFPArg directly. void AddArgAmd64(unsigned canonIndex, unsigned short numSlots, bool isFloatingType); #endif }; typedef MapSHash<void*, CORINFO_METHOD_HANDLE> AddrToMDMap; static AddrToMDMap* s_addrToMDMap; static AddrToMDMap* GetAddrToMdMap(); // In debug, we map to a pair, containing the Thread that inserted it, so we can assert that any given thread only // inserts one stub for a CORINFO_METHOD_HANDLE. struct MethInfo { InterpreterMethodInfo* m_info; #ifdef _DEBUG Thread* m_thread; #endif // _DEBUG }; typedef MapSHash<CORINFO_METHOD_HANDLE, MethInfo> MethodHandleToInterpMethInfoPtrMap; static MethodHandleToInterpMethInfoPtrMap* s_methodHandleToInterpMethInfoPtrMap; static MethodHandleToInterpMethInfoPtrMap* GetMethodHandleToInterpMethInfoPtrMap(); static InterpreterMethodInfo* RecordInterpreterMethodInfoForMethodHandle(CORINFO_METHOD_HANDLE md, InterpreterMethodInfo* methInfo); static InterpreterMethodInfo* MethodHandleToInterpreterMethInfoPtr(CORINFO_METHOD_HANDLE md); public: static unsigned s_interpreterStubNum; private: unsigned CurOffset() { _ASSERTE(m_methInfo->m_ILCode <= m_ILCodePtr && m_ILCodePtr < m_methInfo->m_ILCodeEnd); unsigned res = static_cast<unsigned>(m_ILCodePtr - m_methInfo->m_ILCode); return res; } // We've computed a branch target. Is the target in range? If not, throw an InvalidProgramException. // Otherwise, execute the branch by changing m_ILCodePtr. void ExecuteBranch(BYTE* ilTargetPtr) { if (m_methInfo->m_ILCode <= ilTargetPtr && ilTargetPtr < m_methInfo->m_ILCodeEnd) { m_ILCodePtr = ilTargetPtr; } else { COMPlusThrow(kInvalidProgramException); } } // Private fields: // InterpreterMethodInfo* m_methInfo; InterpreterCEEInfo m_interpCeeInfo; BYTE* m_ILCodePtr; bool m_directCall; BYTE* m_ilArgs; __forceinline InterpreterType GetArgType(unsigned argNum) { return m_methInfo->m_argDescs[argNum].m_type; } __forceinline InterpreterType GetArgTypeNormal(unsigned argNum) { return m_methInfo->m_argDescs[argNum].m_typeStackNormal; } __forceinline BYTE* GetArgAddr(unsigned argNum) { if (!m_directCall) { #if defined(HOST_AMD64) && !defined(UNIX_AMD64_ABI) // In AMD64, a reference to the struct is passed if its size exceeds the word size. // Dereference the arg to get to the ref of the struct. if (GetArgType(argNum).IsLargeStruct(&m_interpCeeInfo)) { return *reinterpret_cast<BYTE**>(&m_ilArgs[m_methInfo->m_argDescs[argNum].m_nativeOffset]); } #endif return &m_ilArgs[m_methInfo->m_argDescs[argNum].m_nativeOffset]; } else { if (GetArgType(argNum).IsLargeStruct(&m_interpCeeInfo)) { return *reinterpret_cast<BYTE**>(&m_ilArgs[m_methInfo->m_argDescs[argNum].m_directOffset]); } else { return &m_ilArgs[m_methInfo->m_argDescs[argNum].m_directOffset]; } } } __forceinline MethodTable* GetMethodTableFromClsHnd(CORINFO_CLASS_HANDLE hnd) { TypeHandle th(hnd); return th.GetMethodTable(); } #ifdef FEATURE_HFA __forceinline BYTE* GetHFARetBuffAddr(unsigned sz) { // Round up to a double boundary: sz = ((sz + sizeof(double) - 1) / sizeof(double)) * sizeof(double); // We rely on the interpreter stub to have pushed "sz" bytes on its stack frame, // below m_ilArgs; return m_ilArgs - sz; } #endif // FEATURE_HFA void* m_stubContext; // Address of the GSCookie value in the current method's frame. GSCookie* m_gsCookieAddr; BYTE* GetFrameBase() { return (m_localVarMemory - sizeof(GSCookie) - m_methInfo->m_largeStructLocalSize); } // m_localVarMemory points to the boundary between the fixed-size slots for the locals // (positive offsets), and the full-sized slots for large struct locals (negative offsets). BYTE* m_localVarMemory; INT64* FixedSizeLocalSlot(unsigned locNum) { return reinterpret_cast<INT64*>(m_localVarMemory) + locNum; } BYTE* LargeStructLocalSlot(unsigned locNum) { BYTE* base = GetFrameBase(); BYTE* addr = base + m_methInfo->m_localDescs[locNum].m_offset; _ASSERTE(IsInLargeStructLocalArea(addr)); return addr; } bool IsInLargeStructLocalArea(void* addr) { void* base = GetFrameBase(); return (base <= addr) && (addr < (static_cast<void*>(m_localVarMemory - sizeof(GSCookie)))); } bool IsInLocalArea(void* addr) { void* base = GetFrameBase(); return (base <= addr) && (addr < static_cast<void*>(reinterpret_cast<INT64*>(m_localVarMemory) + m_methInfo->m_numLocals)); } // Ensures that the operand stack contains no pointers to large struct local slots (by // copying the values out to locations allocated on the large struct stack. void OpStackNormalize(); // The defining property of this word is: if the bottom two bits are not 0x3, then the current operand stack contains no pointers // to large-struct slots for locals. Operationally, we achieve this by taking "OR" of the interpreter types of local variables that have been loaded onto the // operand stack -- if any have been large structs, they will have 0x3 as the low order bits of their interpreter type, and this will be // "sticky." We may sometimes determine that no large struct local pointers are currently on the stack, and reset this word to zero. size_t m_orOfPushedInterpreterTypes; #if COMBINE_OPSTACK_VAL_TYPE struct OpStackValAndType { INT64 m_val; InterpreterType m_type; INT32 m_pad; }; OpStackValAndType* m_operandStackX; #else INT64* m_operandStack; #endif template<typename T> __forceinline T OpStackGet(unsigned ind) { return *OpStackGetAddr<T>(ind); } template<typename T> __forceinline void OpStackSet(unsigned ind, T val) { *OpStackGetAddr<T>(ind) = val; } #if COMBINE_OPSTACK_VAL_TYPE template<typename T> __forceinline T* OpStackGetAddr(unsigned ind) { return reinterpret_cast<T*>(ArgSlotEndianessFixup(reinterpret_cast<ARG_SLOT*>(&m_operandStackX[ind].m_val), sizeof(T))); } __forceinline void* OpStackGetAddr(unsigned ind, size_t sz) { return ArgSlotEndianessFixup(reinterpret_cast<ARG_SLOT*>(&m_operandStackX[ind].m_val), sz); } #else template<typename T> __forceinline T* OpStackGetAddr(unsigned ind) { return reinterpret_cast<T*>(ArgSlotEndianessFixup(reinterpret_cast<ARG_SLOT*>(&m_operandStack[ind]), sizeof(T))); } __forceinline void* OpStackGetAddr(unsigned ind, size_t sz) { return ArgSlotEndianessFixup(reinterpret_cast<ARG_SLOT*>(&m_operandStack[ind]), sz); } #endif __forceinline INT64 GetSmallStructValue(void* src, size_t sz) { _ASSERTE(sz <= sizeof(INT64)); INT64 ret = 0; memcpy(ArgSlotEndianessFixup(reinterpret_cast<ARG_SLOT*>(&ret), sz), src, sz); return ret; } BYTE* m_largeStructOperandStack; size_t m_largeStructOperandStackHt; size_t m_largeStructOperandStackAllocSize; // Allocate "sz" bytes on the large struct operand stack, and return a pointer to where // the structure should be copied. void* LargeStructOperandStackPush(size_t sz); // Deallocate "sz" bytes from the large struct operand stack, unless the corresponding // operand stack value "fromAddr" is a pointer to a local variable. void LargeStructOperandStackPop(size_t sz, void* fromAddr); // Ensures that we can push a struct of size "sz" on the large struct operand stack. void LargeStructOperandStackEnsureCanPush(size_t sz); #ifdef _DEBUG // Returns "true" iff the sum of sizes of large structures on the operand stack // equals "m_largeStructOperandStackHt", which should be an invariant. bool LargeStructStackHeightIsValid(); #endif // _DEBUG // Returns "true" iff the "cit" is 'considered' a valid pointer type for the // architecture. For ex: nativeint/byref and for amd64 longs with loose rules. bool IsValidPointerType(CorInfoType cit); #if !COMBINE_OPSTACK_VAL_TYPE InterpreterType* m_operandStackTypes; #endif #if COMBINE_OPSTACK_VAL_TYPE #if USE_MACRO_FOR_OPSTACKACCESS #define OpStackTypeGet(ind) m_operandStackX[ind].m_type #define OpStackTypeSet(ind, it) m_operandStackX[ind].m_type = it #else __forceinline InterpreterType OpStackTypeGet(unsigned ind) { return m_operandStackX[ind].m_type; } __forceinline void OpStackTypeSet(unsigned ind, InterpreterType it) { _ASSERTE(IsStackNormalType(it.ToCorInfoType())); m_operandStackX[ind].m_type = it; } #endif #else __forceinline InterpreterType OpStackTypeGet(unsigned ind) { return m_operandStackTypes[ind]; } __forceinline void OpStackTypeSet(unsigned ind, InterpreterType it) { _ASSERTE(IsStackNormalType(it.ToCorInfoType())); m_operandStackTypes[ind] = it; } #endif unsigned m_curStackHt; // These are used in searching for finally clauses when we 'leave' a try block: struct LeaveInfo { unsigned m_offset; // The offset of "leave" instructions in try blocks whose finally blocks are being executed. BYTE* m_target; // The location the 'leave' was jumping to -- where execution should resume after all finally's have been executed. unsigned m_nextEHIndex; // The index in the EH table at which the search for the next finally for "lastLeaveOffset" should resume. LeaveInfo(unsigned offset = 0, BYTE* target = NULL) : m_offset(offset), m_target(target), m_nextEHIndex(0) {} }; // This is a stack of the currently in-force "leaves." (Multiple leave's can be being processed when a try-finally occurs // within a finally). Stack<LeaveInfo> m_leaveInfoStack; // Used to track the next filter to scan in case the current // filter doesn't handle the exception. unsigned m_filterNextScan; // Used to record the handler offset for the current filter so it can be used during endfilter. unsigned m_filterHandlerOffset; // The actual offset at which the exception occurred for a filter that might possibly handle it. unsigned m_filterExcILOffset; // This is the exception to rethrow upon exiting the last finally. Object* m_inFlightException; // This must be scanned by GC. // Storing "this" and "typeCtxt" args if necessary. Object* m_thisArg; // This must be scanned by GC. void* m_retBufArg; // This must be scanned by GC: // if the caller is JITted, o.f = Foo(), for o.f a value type, retBuf may be ref o.f. void* m_genericsCtxtArg; // Acquired variable for synchronized methods. unsigned char m_monAcquired; // Holds the security object, for frames that require it. OBJECTREF m_securityObject; ARG_SLOT* m_args; InterpreterType* m_argTypes; unsigned m_argsSize; void* m_callThisArg; // If "m_structRetValITPtr" is non-NULL, then "*m_structRetValITPtr" represents a struct type, and // "m_structRetValTempSpace" is a pointer to a value of that struct type, which must be scanned during GC. InterpreterType* m_structRetValITPtr; void* m_structRetValTempSpace; #ifdef DACCESS_COMPILE void* m_thisExecCache; #else // DACCESS_COMPILE // The proper cache for the current method execution (or else UninitExecCache). ILOffsetToItemCache* m_thisExecCache; // Retrieve the ILoffset->Item cache for the generic instantiation (if any) of the // currently-executing method. If "alloc" is true, allocate one if its not there. ILOffsetToItemCache* GetThisExecCache(bool alloc) { if (m_thisExecCache == UninitExecCache || (m_thisExecCache == NULL && alloc)) { m_thisExecCache = m_methInfo->GetCacheForCall(m_thisArg, m_genericsCtxtArg, alloc); } _ASSERTE(!alloc || m_thisExecCache != NULL); return m_thisExecCache; } // Cache that a call at "iloffset" has the given CallSiteCacheData "callInfo". void CacheCallInfo(unsigned iloffset, CallSiteCacheData* callInfo); // If there's a cached CORINFO_CALL_INFO for the call at the given IL offset, return it, else NULL. CallSiteCacheData* GetCachedCallInfo(unsigned iloffset); void CacheInstanceField(unsigned iloffset, FieldDesc* fld); FieldDesc* GetCachedInstanceField(unsigned iloffset); void CacheStaticField(unsigned iloffset, StaticFieldCacheEntry* pEntry); StaticFieldCacheEntry* GetCachedStaticField(unsigned iloffset); void CacheClassHandle(unsigned ilOffset, CORINFO_CLASS_HANDLE clsHnd); CORINFO_CLASS_HANDLE GetCachedClassHandle(unsigned iloffset); #endif // DACCESS_COMPILE #if INTERP_ILCYCLE_PROFILE // Cycles we want to delete from the current instructions cycle count; e.g., // cycles spent in a callee. unsigned __int64 m_exemptCycles; unsigned __int64 m_startCycles; unsigned short m_instr; void UpdateCycleCount(); #endif // INTERP_ILCYCLE_PROFILE #ifdef _DEBUG // These collectively record all the interpreter method infos we've created. static InterpreterMethodInfo** s_interpMethInfos; static unsigned s_interpMethInfosAllocSize; static unsigned s_interpMethInfosCount; static void AddInterpMethInfo(InterpreterMethodInfo* methInfo); // Print any end-of-run summary information we've collected, and want // printed. // Both methods below require that "mi0" and "mi1" are actually "InterpreterMethodInfo*"s. // Returns -1, 0, or 1, depending on whether "mi0->m_invocations" is less than, // equal, or greater than "mi1->m_invocations.". static int _cdecl CompareMethInfosByInvocations(const void* mi0, const void* mi1); #if INTERP_PROFILE // Returns 1, 0, or -1, depending on whether "mi0->m_totIlInstructionsExeced" is less than, // equal, or greater than "mi1->m_totIlInstructionsExeced.". (Note that this enables a descending sort.) static int _cdecl CompareMethInfosByILInstrs(const void* mi0, const void* mi1); #endif // INTERP_PROFILE #endif // _DEBUG private: static ConfigDWORD s_PrintPostMortemFlag; public: static void PrintPostMortemData(); #if INTERP_TRACING private: // Returns a string name of the il operation at "ILCodePtr". static const char* ILOp(BYTE* ilCodePtr); static const char* ILOp1Byte(unsigned short ilInstrVal); static const char* ILOp2Byte(unsigned short ilInstrVal); // Prints a representation of the operand stack. void PrintOStack(); // Prints a representation of the arguments. void PrintArgs(); // Prints a representation of the locals. void PrintLocals(); // Helper functions for the above: // Print the value at ostack position "index". void PrintOStackValue(unsigned index); // Print the value of the argument number "argNum". void PrintArgValue(unsigned argNum); // Requires that "valAddr" point to a location containing a value of type // "cit", and prints that value. void PrintValue(InterpreterType cit, BYTE* valAddr); public: static inline FILE* GetLogFile(); private: static FILE* s_InterpreterLogFile; static ConfigDWORD s_DumpInterpreterStubsFlag; static ConfigDWORD s_TraceInterpreterEntriesFlag; static ConfigDWORD s_TraceInterpreterILFlag; static ConfigDWORD s_TraceInterpreterOstackFlag; static ConfigDWORD s_TraceInterpreterVerboseFlag; static ConfigDWORD s_TraceInterpreterJITTransitionFlag; static ConfigDWORD s_InterpreterStubMin; static ConfigDWORD s_InterpreterStubMax; // The total number of method invocations. static LONG s_totalInvocations; // The total number of calls made by interpreted code. static LONG s_totalInterpCalls; static LONG s_totalInterpCallsToGetters; static LONG s_totalInterpCallsToDeadSimpleGetters; static LONG s_totalInterpCallsToDeadSimpleGettersShortCircuited; static LONG s_totalInterpCallsToSetters; static LONG s_totalInterpCallsToIntrinsics; static LONG s_totalInterpCallsToIntrinsicsUnhandled; enum ResolveTokenKind { RTK_Undefined, RTK_Constrained, RTK_NewObj, RTK_NewArr, RTK_LdToken, RTK_LdFtn, RTK_LdVirtFtn, RTK_SFldAddr, RTK_LdElem, RTK_Call, RTK_LdObj, RTK_StObj, RTK_CpObj, RTK_InitObj, RTK_IsInst, RTK_CastClass, RTK_MkRefAny, RTK_RefAnyVal, RTK_Sizeof, RTK_StElem, RTK_Box, RTK_Unbox, RTK_UnboxAny, RTK_LdFld, RTK_LdFldA, RTK_StFld, RTK_FindClass, RTK_CheckHandlesException, RTK_Count }; static const char* s_tokenResolutionKindNames[RTK_Count]; static LONG s_tokenResolutionOpportunities[RTK_Count]; static LONG s_tokenResolutionCalls[RTK_Count]; #endif // INTERP_TRACING #if INTERP_ILINSTR_PROFILE static unsigned short s_ILInstrCategories[512]; static int s_ILInstrExecs[256]; static int s_ILInstrExecsByCategory[512]; #if INTERP_ILCYCLE_PROFILE static unsigned __int64 s_ILInstrCyclesByCategory[512]; #endif // INTERP_ILCYCLE_PROFILE static const unsigned CountIlInstr2Byte = 0x22; static int s_ILInstr2ByteExecs[CountIlInstr2Byte]; #if INTERP_ILCYCLE_PROFILE static unsigned __int64 s_ILInstrCycles[512]; // XXX static unsigned __int64 s_callCycles; static unsigned s_calls; #endif // INTERP_ILCYCLE_PROFILE #endif // INTERP_ILINSTR_PROFILE // Non-debug-only statics. static ConfigMethodSet s_InterpretMeths; static ConfigMethodSet s_InterpretMethsExclude; static ConfigDWORD s_InterpretMethHashMin; static ConfigDWORD s_InterpretMethHashMax; static ConfigDWORD s_InterpreterJITThreshold; static ConfigDWORD s_InterpreterDoLoopMethodsFlag; static bool s_InterpreterDoLoopMethods; static ConfigDWORD s_InterpreterUseCachingFlag; static bool s_InterpreterUseCaching; static ConfigDWORD s_InterpreterLooseRulesFlag; static bool s_InterpreterLooseRules; static CrstExplicitInit s_methodCacheLock; static CrstExplicitInit s_interpStubToMDMapLock; // True iff a "constrained" prefix has preceded a call. bool m_constrainedFlag; // True iff a "volatile" prefixe precedes a memory reference. bool m_volatileFlag; // If there has been a "constrained" prefix, this is initialized // with the token of the constraint class. CORINFO_RESOLVED_TOKEN m_constrainedResolvedToken; // True iff a "readonly" prefix has preceded a ldelema. bool m_readonlyFlag; // Data structures related to localloc. class LocAllocData { typedef void* PVoid; unsigned m_locAllocSize; // The currently allocated # elements in m_locAllocs unsigned m_locAllocCurIdx; // Number of elements of m_locAllocs in use; 0 <= m_locAllocCurIdx < m_locAllocSize void** m_locAllocs; // Always non-null in a constructed LocAllocData. static const unsigned DefaultAllocs = 1; unsigned EnsureIdx() { if (m_locAllocCurIdx == m_locAllocSize) { unsigned newSize = m_locAllocSize * 2; void** newLocAllocs = new PVoid[newSize]; for (unsigned j = 0; j < m_locAllocCurIdx; j++) { newLocAllocs[j] = m_locAllocs[j]; } m_locAllocSize = newSize; delete[] m_locAllocs; m_locAllocs = newLocAllocs; } return m_locAllocCurIdx++; // Note that we're returning the value before post-increment. } public: LocAllocData() : m_locAllocSize(DefaultAllocs), m_locAllocCurIdx(0) { m_locAllocs = new PVoid[DefaultAllocs]; memset(m_locAllocs, 0, DefaultAllocs * sizeof(void*)); } void* Alloc(NativeUInt sz) { unsigned idx = EnsureIdx(); void* res = new char[sz]; // We only *have* to do this if initlocals is set, but no harm in always doing it. memset(res, 0, sz); m_locAllocs[idx] = res; return res; } ~LocAllocData() { if (m_locAllocs != NULL) { for (unsigned i = 0; i < m_locAllocCurIdx; i++) { delete[] reinterpret_cast<char*>(m_locAllocs[i]); } } delete[] m_locAllocs; } }; LocAllocData* m_locAllocData; LocAllocData* GetLocAllocData() { if (m_locAllocData == NULL) { m_locAllocData = new LocAllocData(); } return m_locAllocData; } // Search the current method's exception table, starting at "leaveEHIndex", for the first finally clause // for a try block that covers "lastLeaveOffset". If one is found, sets m_ILCodePtr to the start of that // finally clause, updates "leaveEHIndex" to be the next index after the found clause in the exception // table, and returns true. Otherwise, if no applicable finally clause is found, returns false. bool SearchForCoveringFinally(); void LdIcon(INT32 c); void LdLcon(INT64 c); void LdR4con(INT32 c); void LdR8con(INT64 c); void LdArg(int argNum); void LdArgA(int argNum); void StArg(int argNum); __forceinline void LdLoc(int locNum); void LdLocA(int locNum); __forceinline void StLoc(int locNum); // Requires that "*addr" contain a value of type "tp"; reads that value and // pushes it on the operand stack. __forceinline void LdFromMemAddr(void* addr, InterpreterType tp); // Requires that "addr" is the address of a local var or argument location. // Pops the value on the operand stack, assumed to be of the given "tp", and stores // in "*addr". __forceinline void StToLocalMemAddr(void* addr, InterpreterType tp); void LdNull(); // This requires that the width of "T" is at least 4 bytes. template<typename T, CorInfoType cit> void LdInd(); // This requires that the width of "T" is less than 4 bytes (and loads it as an INT32). template<typename T, bool isUnsigned> void LdIndShort(); void LdIndFloat(); // Use this for non-object-ref types, and StInd_Ref for object refs. template<typename T> void StInd(); void StInd_Ref(); // Load/store instance/static fields. // If non-NULL, we've determined the field to be loaded by other means (e.g., we've identified a // "dead simple" property getter). In this case, use this FieldDesc*, otherwise, look up via token // or cache. void LdFld(FieldDesc* fld = NULL); void LdFldA(); void LdSFld(); void LdSFldA(); void StFld(); void StSFld(); // Helper method used by the static field methods above. // Requires that the code stream be pointing to a LDSFLD, LDSFLDA, or STSFLD. // The "accessFlgs" variable should indicate which, by which of the CORINFO_ACCESS_GET, // CORINFO_ACCESS_GET, and CORINFO_ACCESS_ADDRESS bits are set. // Sets *pStaticFieldAddr, which must be a pointer to memory protected as a byref) to the address of the static field, // sets *pit to the InterpreterType of the field, // sets *pFldSize to the size of the field, and sets *pManagedMem to true iff the address is in managed memory (this is // false only if the static variable is an "RVA"). (Increments the m_ILCodePtr of 'this' by 5, the // assumed size of all the listed instructions. __forceinline void StaticFldAddr(CORINFO_ACCESS_FLAGS accessFlgs, /*out (byref)*/void** pStaticFieldAddr, /*out*/InterpreterType* pit, /*out*/UINT* pFldSize, /*out*/bool* pManagedMem); // We give out the address of this as the address for an "intrinsic static Zero". static INT64 IntrinsicStaticZero; // The version above does caching; this version always does the work. Returns "true" iff the results // are cacheable. bool StaticFldAddrWork(CORINFO_ACCESS_FLAGS accessFlgs, /*out (byref)*/void** pStaticFieldAddr, /*out*/InterpreterType* pit, /*out*/UINT* pFldSize, /*out*/bool* pManagedMem); // Ensure that pMT has been initialized (including running it's .cctor). static void EnsureClassInit(MethodTable* pMT); // Load/store array elements, get length. "T" should be the element // type of the array (as indicated by a LDELEM opcode with a type); "IsObjType" should // be true iff T is an object type, and "cit" should be the stack-normal CorInfoType // to push on the type stack. template<typename T, bool IsObjType, CorInfoType cit> void LdElemWithType(); // Load the address of an array element. template<typename T, bool IsObjType> void StElemWithType(); template<bool takeAddr> void LdElem(); void StElem(); void InitBlk(); void CpBlk(); void Box(); void UnboxAny(); void Unbox(); // Requires that operand stack location "i" contain a byref to a value of the struct type // "valCls". Boxes the referent of that byref, and substitutes the resulting object pointer // at opstack location "i." void BoxStructRefAt(unsigned ind, CORINFO_CLASS_HANDLE valCls); void Throw(); void Rethrow(); void EndFilter(); void LdLen(); // Perform a normal (non-constructor) call. The "virtualCall" argument indicates whether the // call should be virtual. void DoCall(bool virtualCall); // Perform a call. For normal (non-constructor) calls, all optional args should be // NULL (the default). For constructors, "thisArg" should be a this pointer (that is not on the operand stack), // and "callInfoPtr" should be the callInfo describing the constructor. There's a special case here: for "VAROBJSIZE" constructors // (which currently are defined for String), we want to explicitly pass NULL to the (pseudo) constructor. So passing // the special value "0x1" as "thisArg" will cause NULL to be pushed. void DoCallWork(bool virtualCall, void* thisArg = NULL, CORINFO_RESOLVED_TOKEN* methTokPtr = NULL, CORINFO_CALL_INFO* callInfoPtr = NULL); // Do the call-indirect operation. void CallI(); // Analyze the given method to see if it is a "dead simple" property getter: // * if instance, ldarg.0, ldfld, ret. // * if static, ldstfld ret. // More complicated forms in DBG. Sets *offsetOfLd" to the offset of the ldfld or ldstfld instruction. static bool IsDeadSimpleGetter(CEEInfo* info, MethodDesc* pMD, size_t* offsetOfLd); static const unsigned ILOffsetOfLdFldInDeadSimpleInstanceGetterDbg = 2; static const unsigned ILOffsetOfLdFldInDeadSimpleInstanceGetterOpt = 1; static const unsigned ILOffsetOfLdSFldInDeadSimpleStaticGetter = 0; // Here we handle a few intrinsic calls directly. void DoStringLength(); void DoStringGetChar(); void DoGetTypeFromHandle(); void DoByReferenceCtor(); void DoByReferenceValue(); void DoSIMDHwAccelerated(); void DoGetIsSupported(); // Returns the proper generics context for use in resolving tokens ("precise" in the sense of including generic instantiation // information). CORINFO_CONTEXT_HANDLE m_preciseGenericsContext; CORINFO_CONTEXT_HANDLE GetPreciseGenericsContext() { if (m_preciseGenericsContext == NULL) { m_preciseGenericsContext = m_methInfo->GetPreciseGenericsContext(m_thisArg, m_genericsCtxtArg); } return m_preciseGenericsContext; } // Process the "CONSTRAINED" prefix, recording the constraint on the "this" parameter. void RecordConstrainedCall(); // Emit a barrier if the m_volatile flag is set, and reset the flag. void BarrierIfVolatile() { if (m_volatileFlag) { MemoryBarrier(); m_volatileFlag = false; } } enum BinaryArithOpEnum { BA_Add, BA_Sub, BA_Mul, BA_Div, BA_Rem }; template<int op> __forceinline void BinaryArithOp(); // "IsIntType" must be true iff "T" is an integral type, and "cit" must correspond to // "T". "TypeIsUnchanged" implies that the proper type is already on the operand type stack. template<int op, typename T, bool IsIntType, CorInfoType cit, bool TypeIsUnchanged> __forceinline void BinaryArithOpWork(T val1, T val2); // "op" is a BinaryArithOpEnum above; actually, must be one "BA_Add", "BA_Sub", "BA_Mul". template<int op, bool asUnsigned> void BinaryArithOvfOp(); template<int op, typename T, CorInfoType cit, bool TypeIsUnchanged> void BinaryArithOvfOpWork(T val1, T val2); INT32 RemFunc(INT32 v1, INT32 v2) { return v1 % v2; } INT64 RemFunc(INT64 v1, INT64 v2) { return v1 % v2; } float RemFunc(float v1, float v2); double RemFunc(double v1, double v2); enum BinaryIntOpEnum { BIO_And, BIO_DivUn, BIO_Or, BIO_RemUn, BIO_Xor }; template<int op> void BinaryIntOp(); template<int op, typename T, CorInfoType cit, bool TypeIsUnchanged> void BinaryIntOpWork(T val1, T val2); template<int op> void ShiftOp(); template<int op, typename T, typename UT> void ShiftOpWork(unsigned op1idx, CorInfoType cit2); void Neg(); void Not(); // "T" should be the type indicated by the opcode. // "TIsUnsigned" should be true if "T" is an unsigned type. // "TCanHoldPtr" should be true if the type can hold a pointer (true for NativeInt and Long). // "TIsShort" should be true if "T" is less wide than Int32. // "cit" should be the *stack-normal* type of the converted value; even if "TIsShort", "cit" should be CORINFO_TYPE_INT. template<typename T, bool TIsUnsigned, bool TCanHoldPtr, bool TIsShort, CorInfoType cit> void Conv(); void ConvRUn(); // This version is for conversion to integral types. template<typename T, INT64 TMin, UINT64 TMax, bool TCanHoldPtr, CorInfoType cit> void ConvOvf(); // This version is for conversion to integral types. template<typename T, INT64 TMin, UINT64 TMax, bool TCanHoldPtr, CorInfoType cit> void ConvOvfUn(); void LdObj(); void LdObjValueClassWork(CORINFO_CLASS_HANDLE valueClsHnd, unsigned ind, void* src); void CpObj(); void StObj(); void InitObj(); void LdStr(); void NewObj(); void NewArr(); void IsInst(); void CastClass(); void MkRefany(); void RefanyType(); void RefanyVal(); void CkFinite(); void LdToken(); void LdFtn(); void LdVirtFtn(); // The JIT/EE machinery for transforming delegate constructor calls requires the // CORINFO_METHOD_HANDLE of a method. Usually, the method will be provided by a previous LDFTN/LDVIRTFTN. // In the JIT, we fold that previous instruction and the delegate constructor into a single tree, before morphing. // At this time, the loaded function is still in the form of a CORINFO_METHOD_HANDLE. At morph time, delegate constructor is transformed, // looking into the argument trees to find this handle. LDFTN's that are not removed this way are morphed to have actual native code addresses. // To support both of these needs, LDFTN will push the native code address of a method, as uses that actually need the value to invoke or store in // data structures require, but it will also ensure that this parallel stack is allocated, and set the corresponding index to hold the method handle. // When we call a delegate constructor, we find the method handle on this stack. CORINFO_METHOD_HANDLE* m_functionPointerStack; CORINFO_METHOD_HANDLE* GetFunctionPointerStack() { if (m_functionPointerStack == NULL) { m_functionPointerStack = new CORINFO_METHOD_HANDLE[m_methInfo->m_maxStack]; for (unsigned i = 0; i < m_methInfo->m_maxStack; i++) { m_functionPointerStack[i] = NULL; } } return m_functionPointerStack; } void Sizeof(); void LocAlloc(); #if INTERP_ILINSTR_PROFILE static void SetILInstrCategories(); // This type is used in sorting il instructions in a profile. struct InstrExecRecord { unsigned short m_instr; bool m_is2byte; unsigned m_execs; #if INTERP_ILCYCLE_PROFILE unsigned __int64 m_cycles; #endif // INTERP_ILCYCLE_PROFILE static int _cdecl Compare(const void* v0, const void* v1) { InstrExecRecord* iep0 = (InstrExecRecord*)v0; InstrExecRecord* iep1 = (InstrExecRecord*)v1; #if INTERP_ILCYCLE_PROFILE if (iep0->m_cycles > iep1->m_cycles) return -1; else if (iep0->m_cycles == iep1->m_cycles) return 0; else return 1; #else if (iep0->m_execs > iep1->m_execs) return -1; else if (iep0->m_execs == iep1->m_execs) return 0; else return 1; #endif // INTERP_ILCYCLE_PROFILE } }; // Prints the given array "recs", assumed to already be sorted. static void PrintILProfile(InstrExecRecord* recs, unsigned totInstrs #if INTERP_ILCYCLE_PROFILE , unsigned __int64 totCycles #endif // INTERP_ILCYCLE_PROFILE ); #endif // INTERP_ILINSTR_PROFILE static size_t GetTypedRefSize(CEEInfo* info); static CORINFO_CLASS_HANDLE GetTypedRefClsHnd(CEEInfo* info); static InterpreterType GetTypedRefIT(CEEInfo* info); OBJECTREF TypeHandleToTypeRef(TypeHandle* pth); CorInfoType GetTypeForPrimitiveValueClass(CORINFO_CLASS_HANDLE clsHnd); static bool s_initialized; static bool s_compilerStaticsInitialized; // This is the class handle for the struct type TypedRef (aka "Refany"). static CORINFO_CLASS_HANDLE s_TypedRefClsHnd; // This is the InterpreterType for the struct type TypedRef (aka "Refany"). static InterpreterType s_TypedRefIT; // And this is the size of that struct. static size_t s_TypedRefSize; // This returns the class corresponding to the token, of kind "tokKind", at "codePtr". If this // includes any runtime lookup via a generics context parameter, does that. CORINFO_CLASS_HANDLE GetTypeFromToken(BYTE* codePtr, CorInfoTokenKind tokKind InterpTracingArg(ResolveTokenKind rtk)); // Calls m_interpCeeInfo.resolveToken inline void ResolveToken(CORINFO_RESOLVED_TOKEN* resTok, mdToken token, CorInfoTokenKind tokenType InterpTracingArg(ResolveTokenKind rtk)); inline FieldDesc* FindField(unsigned metaTok InterpTracingArg(ResolveTokenKind rtk)); inline CORINFO_CLASS_HANDLE FindClass(unsigned metaTok InterpTracingArg(ResolveTokenKind rtk)); enum CompareOpEnum { CO_EQ, CO_GT, CO_GT_UN, CO_LT, CO_LT_UN }; // It does not help making these next two inline functions (taking the // template arg as a "real" arg). template<int compOp> void CompareOp(); // Requires that the m_curStackHt is at least op1Idx+2. // Returns the result (0 or 1) of the comparison "opStack[op1Idx] op opStack[op1Idx + 1]". template<int compOp> INT32 CompareOpRes(unsigned op1Idx); // Making this inline, by making its arguments real arguments, // and using __forceinline didn't result in material difference. template<bool val, int targetLen> void BrOnValue(); // A worker function for BrOnValue. Assumes that "shouldBranch" indicates whether // a branch should be taken, and that "targetLen" is the length of the branch offset (1 or 4). // Updates "m_ILCodePtr" to the branch target if "shouldBranch" is true, or else // he next instruction (+ 1 + targetLength). __forceinline void BrOnValueTakeBranch(bool shouldBranch, int targetLen); template<int compOp, bool reverse, int targetLen> void BrOnComparison(); inline static INT8 getI1(const BYTE * ptr) { return *(INT8*)ptr; } inline static UINT16 getU2LittleEndian(const BYTE * ptr) { return VAL16(*(UNALIGNED UINT16*)ptr); } inline static UINT32 getU4LittleEndian(const BYTE * ptr) { return VAL32(*(UNALIGNED UINT32*)ptr); } inline static INT32 getI4LittleEndian(const BYTE * ptr) { return VAL32(*(UNALIGNED INT32*)ptr); } inline static INT64 getI8LittleEndian(const BYTE * ptr) { return VAL64(*(UNALIGNED INT64*)ptr); } void VerificationError(const char* msg); void ThrowDivideByZero(); void ThrowSysArithException(); void ThrowNullPointerException(); void ThrowOverflowException(); void ThrowArrayBoundsException(); void ThrowInvalidCastException(); void ThrowStackOverflow(); void ThrowOnInvalidPointer(void* ptr); #ifdef _DEBUG bool TOSIsPtr(); #endif #if INTERP_TRACING // Code copied from eeinterface.cpp in "compiler". Should be common... const char* eeGetMethodFullName(CORINFO_METHOD_HANDLE hnd); #endif // INTERP_TRACING }; #if defined(HOST_X86) inline unsigned short Interpreter::NumberOfIntegerRegArgs() { return 2; } #elif defined(HOST_AMD64) unsigned short Interpreter::NumberOfIntegerRegArgs() { #if defined(UNIX_AMD64_ABI) return 6; #else return 4; #endif } #elif defined(HOST_ARM) unsigned short Interpreter::NumberOfIntegerRegArgs() { return 4; } #elif defined(HOST_ARM64) unsigned short Interpreter::NumberOfIntegerRegArgs() { return 8; } #else #error Unsupported architecture. #endif #endif // INTERPRETER_H_DEFINED
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #ifndef INTERPRETER_H_DEFINED #define INTERPRETER_H_DEFINED 1 #include "corjit.h" #include "corinfo.h" #include "codeman.h" #include "jitinterface.h" #include "stack.h" #include "crst.h" #include "callhelpers.h" #include "codeversion.h" #include "clr_std/type_traits" typedef SSIZE_T NativeInt; typedef SIZE_T NativeUInt; typedef SIZE_T NativePtr; // Determines whether we interpret IL stubs. (We might disable this selectively for // some architectures, perhaps.) #define INTERP_ILSTUBS 1 // If this is set, we keep track of extra information about IL instructions executed per-method. #define INTERP_PROFILE 0 // If this is set, we track the distribution of IL instructions. #define INTERP_ILINSTR_PROFILE 0 #define INTERP_ILCYCLE_PROFILE 0 #if INTERP_ILCYCLE_PROFILE #if !INTERP_ILINSTR_PROFILE #error INTERP_ILCYCLE_PROFILE may only be set if INTERP_ILINSTR_PROFILE is also set. #endif #endif #if defined(_DEBUG) || INTERP_ILINSTR_PROFILE // I define "INTERP_TRACING", rather than just using _DEBUG, so that I can easily make a build // in which tracing is enabled in retail. #define INTERP_TRACING 1 #else #define INTERP_TRACING 0 #endif // defined(_DEBUG) || defined(INTERP_ILINSTR_PROFILE) #if INTERP_TRACING #define INTERPLOG(...) if (s_TraceInterpreterVerboseFlag.val(CLRConfig::INTERNAL_TraceInterpreterVerbose)) { fprintf(GetLogFile(), __VA_ARGS__); } #else #define INTERPLOG(...) #endif #if INTERP_TRACING #define InterpTracingArg(x) ,x #else #define InterpTracingArg(x) #endif #define FEATURE_INTERPRETER_DEADSIMPLE_OPT 0 #define NYI_INTERP(msg) _ASSERTE_MSG(false, msg) // I wanted to define NYI_INTERP as the following in retail: // #define NYI_INTERP(msg) _ASSERTE_ALL_BUILDS(__FILE__, false) // but doing so gave a very odd unreachable code error. // To allow keeping a pointer (index) to the vararg cookie argument to implement arglist. // Use sentinel value of NO_VA_ARGNUM. #define NO_VA_ARGNUM UINT_MAX // First, a set of utility routines on CorInfoTypes. // Returns "true" iff "cit" is "stack-normal": all integer types with byte size less than 4 // are folded to CORINFO_TYPE_INT; all remaining unsigned types are folded to their signed counterparts. bool IsStackNormalType(CorInfoType cit); // Returns the stack-normal CorInfoType that contains "cit". CorInfoType CorInfoTypeStackNormalize(CorInfoType cit); // Returns the (byte) size of "cit". Requires that "cit" is not a CORINFO_TYPE_VALUECLASS. size_t CorInfoTypeSize(CorInfoType cit); // Returns true iff "cit" is an unsigned integral type. bool CorInfoTypeIsUnsigned(CorInfoType cit); // Returns true iff "cit" is an integral type. bool CorInfoTypeIsIntegral(CorInfoType cit); // Returns true iff "cet" is an unsigned integral type. bool CorElemTypeIsUnsigned(CorElementType cet); // Returns true iff "cit" is a floating-point type. bool CorInfoTypeIsFloatingPoint(CorInfoType cit); // Returns true iff "cihet" is a floating-point type (float or double). // TODO: Handle Vector64, Vector128? bool CorInfoTypeIsFloatingPoint(CorInfoHFAElemType cihet); // Returns true iff "cit" is a pointer type (mgd/unmgd pointer, or native int). bool CorInfoTypeIsPointer(CorInfoType cit); // Requires that "cit" is stack-normal; returns its (byte) size. inline size_t CorInfoTypeStackNormalSize(CorInfoType cit) { _ASSERTE(IsStackNormalType(cit)); return CorInfoTypeSize(cit); } inline unsigned getClassSize(CORINFO_CLASS_HANDLE clsHnd) { TypeHandle VMClsHnd(clsHnd); return VMClsHnd.GetSize(); } // The values of this enumeration are in one-to-one correspondence with CorInfoType -- // just shifted so that they're the value stored in an interpreter type for non-value-class // CorinfoTypes. enum CorInfoTypeShifted { CORINFO_TYPE_SHIFTED_UNDEF = unsigned(CORINFO_TYPE_UNDEF) << 2, //0x0 << 2 = 0x0 CORINFO_TYPE_SHIFTED_VOID = unsigned(CORINFO_TYPE_VOID) << 2, //0x1 << 2 = 0x4 CORINFO_TYPE_SHIFTED_BOOL = unsigned(CORINFO_TYPE_BOOL) << 2, //0x2 << 2 = 0x8 CORINFO_TYPE_SHIFTED_CHAR = unsigned(CORINFO_TYPE_CHAR) << 2, //0x3 << 2 = 0xC CORINFO_TYPE_SHIFTED_BYTE = unsigned(CORINFO_TYPE_BYTE) << 2, //0x4 << 2 = 0x10 CORINFO_TYPE_SHIFTED_UBYTE = unsigned(CORINFO_TYPE_UBYTE) << 2, //0x5 << 2 = 0x14 CORINFO_TYPE_SHIFTED_SHORT = unsigned(CORINFO_TYPE_SHORT) << 2, //0x6 << 2 = 0x18 CORINFO_TYPE_SHIFTED_USHORT = unsigned(CORINFO_TYPE_USHORT) << 2, //0x7 << 2 = 0x1C CORINFO_TYPE_SHIFTED_INT = unsigned(CORINFO_TYPE_INT) << 2, //0x8 << 2 = 0x20 CORINFO_TYPE_SHIFTED_UINT = unsigned(CORINFO_TYPE_UINT) << 2, //0x9 << 2 = 0x24 CORINFO_TYPE_SHIFTED_LONG = unsigned(CORINFO_TYPE_LONG) << 2, //0xa << 2 = 0x28 CORINFO_TYPE_SHIFTED_ULONG = unsigned(CORINFO_TYPE_ULONG) << 2, //0xb << 2 = 0x2C CORINFO_TYPE_SHIFTED_NATIVEINT = unsigned(CORINFO_TYPE_NATIVEINT) << 2, //0xc << 2 = 0x30 CORINFO_TYPE_SHIFTED_NATIVEUINT = unsigned(CORINFO_TYPE_NATIVEUINT) << 2, //0xd << 2 = 0x34 CORINFO_TYPE_SHIFTED_FLOAT = unsigned(CORINFO_TYPE_FLOAT) << 2, //0xe << 2 = 0x38 CORINFO_TYPE_SHIFTED_DOUBLE = unsigned(CORINFO_TYPE_DOUBLE) << 2, //0xf << 2 = 0x3C CORINFO_TYPE_SHIFTED_STRING = unsigned(CORINFO_TYPE_STRING) << 2, //0x10 << 2 = 0x40 CORINFO_TYPE_SHIFTED_PTR = unsigned(CORINFO_TYPE_PTR) << 2, //0x11 << 2 = 0x44 CORINFO_TYPE_SHIFTED_BYREF = unsigned(CORINFO_TYPE_BYREF) << 2, //0x12 << 2 = 0x48 CORINFO_TYPE_SHIFTED_VALUECLASS = unsigned(CORINFO_TYPE_VALUECLASS) << 2, //0x13 << 2 = 0x4C CORINFO_TYPE_SHIFTED_CLASS = unsigned(CORINFO_TYPE_CLASS) << 2, //0x14 << 2 = 0x50 CORINFO_TYPE_SHIFTED_REFANY = unsigned(CORINFO_TYPE_REFANY) << 2, //0x15 << 2 = 0x54 CORINFO_TYPE_SHIFTED_VAR = unsigned(CORINFO_TYPE_VAR) << 2, //0x16 << 2 = 0x58 }; class InterpreterType { // We use this typedef, but the InterpreterType is actually encoded. We assume that the two // low-order bits of a "real" CORINFO_CLASS_HANDLE are zero, then use them as follows: // 0x0 ==> if "ci" is a non-struct CORINFO_TYPE_* value, m_tp contents are (ci << 2). // 0x1, 0x3 ==> is a CORINFO_CLASS_HANDLE "sh" for a struct type, or'd with 0x1 and possibly 0x2. // 0x2 is added to indicate that an instance does not fit in a INT64 stack slot on the plaform, and // should be referenced via a level of indirection. // 0x2 (exactly) indicates that it is a "native struct type". // CORINFO_CLASS_HANDLE m_tp; public: // Default ==> undefined. InterpreterType() : m_tp(reinterpret_cast<CORINFO_CLASS_HANDLE>((static_cast<intptr_t>(CORINFO_TYPE_UNDEF) << 2))) {} // Requires that "cit" is not CORINFO_TYPE_VALUECLASS. InterpreterType(CorInfoType cit) : m_tp(reinterpret_cast<CORINFO_CLASS_HANDLE>((static_cast<intptr_t>(cit) << 2))) { _ASSERTE(cit != CORINFO_TYPE_VALUECLASS); } // Requires that "cet" is not ELEMENT_TYPE_VALUETYPE. InterpreterType(CorElementType cet) : m_tp(reinterpret_cast<CORINFO_CLASS_HANDLE>((static_cast<intptr_t>(CEEInfo::asCorInfoType(cet)) << 2))) { _ASSERTE(cet != ELEMENT_TYPE_VALUETYPE); } InterpreterType(CEEInfo* comp, CORINFO_CLASS_HANDLE sh) { GCX_PREEMP(); // TODO: might wish to make a different constructor, for the cases where this is possible... TypeHandle typHnd(sh); if (typHnd.IsNativeValueType()) { intptr_t shAsInt = reinterpret_cast<intptr_t>(sh); _ASSERTE((shAsInt & 0x1) == 0); // The 0x2 bit might already be set by the VM! This is ok, because it's only set for native value types. This is a bit slimey... m_tp = reinterpret_cast<CORINFO_CLASS_HANDLE>(shAsInt | 0x2); } else { CorInfoType cit = comp->getTypeForPrimitiveValueClass(sh); if (cit != CORINFO_TYPE_UNDEF) { m_tp = reinterpret_cast<CORINFO_CLASS_HANDLE>(static_cast<intptr_t>(cit) << 2); } else { _ASSERTE((comp->getClassAttribs(sh) & CORINFO_FLG_VALUECLASS) != 0); intptr_t shAsInt = reinterpret_cast<intptr_t>(sh); _ASSERTE((shAsInt & 0x3) == 0); intptr_t bits = 0x1; // All value classes (structs) get 0x1 set. if (getClassSize(sh) > sizeof(INT64)) { bits |= 0x2; // "Large" structs get 0x2 set, also. } m_tp = reinterpret_cast<CORINFO_CLASS_HANDLE>(shAsInt | bits); } } } bool operator==(const InterpreterType& it2) const { return m_tp == it2.m_tp; } bool operator!=(const InterpreterType& it2) const { return m_tp != it2.m_tp; } CorInfoType ToCorInfoType() const { LIMITED_METHOD_CONTRACT; intptr_t iTypeAsInt = reinterpret_cast<intptr_t>(m_tp); if ((iTypeAsInt & 0x3) == 0x0) { return static_cast<CorInfoType>(iTypeAsInt >> 2); } // Is a class or struct (or refany?). else { return CORINFO_TYPE_VALUECLASS; } } CorInfoType ToCorInfoTypeNotStruct() const { LIMITED_METHOD_CONTRACT; _ASSERTE_MSG((reinterpret_cast<intptr_t>(m_tp) & 0x3) == 0x0, "precondition: not a struct type."); intptr_t iTypeAsInt = reinterpret_cast<intptr_t>(m_tp); return static_cast<CorInfoType>(iTypeAsInt >> 2); } CorInfoTypeShifted ToCorInfoTypeShifted() const { LIMITED_METHOD_CONTRACT; _ASSERTE_MSG((reinterpret_cast<intptr_t>(m_tp) & 0x3) == 0x0, "precondition: not a struct type."); return static_cast<CorInfoTypeShifted>(reinterpret_cast<size_t>(m_tp)); } CORINFO_CLASS_HANDLE ToClassHandle() const { LIMITED_METHOD_CONTRACT; intptr_t asInt = reinterpret_cast<intptr_t>(m_tp); _ASSERTE((asInt & 0x3) != 0); return reinterpret_cast<CORINFO_CLASS_HANDLE>(asInt & (~0x3)); } size_t AsRaw() const // Just hand out the raw bits. Be careful using this! Use something else if you can! { LIMITED_METHOD_CONTRACT; return reinterpret_cast<size_t>(m_tp); } // Returns the stack-normalized type for "this". InterpreterType StackNormalize() const; // Returns the (byte) size of "this". Requires "ceeInfo" for the struct case. __forceinline size_t Size(CEEInfo* ceeInfo) const { LIMITED_METHOD_CONTRACT; intptr_t asInt = reinterpret_cast<intptr_t>(m_tp); intptr_t asIntBits = (asInt & 0x3); if (asIntBits == 0) { return CorInfoTypeSize(ToCorInfoType()); } else if (asIntBits == 0x2) { // Here we're breaking abstraction, and taking advantage of the fact that 0x2 // is the low-bit encoding of "native struct type" both for InterpreterType and for // TypeHandle. TypeHandle typHnd(m_tp); _ASSERTE(typHnd.IsNativeValueType()); return typHnd.AsNativeValueType()->GetNativeSize(); } else { return getClassSize(ToClassHandle()); } } __forceinline size_t SizeNotStruct() const { LIMITED_METHOD_CONTRACT; _ASSERTE_MSG((reinterpret_cast<intptr_t>(m_tp) & 0x3) == 0, "Precondition: is not a struct type!"); return CorInfoTypeSize(ToCorInfoTypeNotStruct()); } // Requires that "it" is stack-normal; returns its (byte) size. size_t StackNormalSize() const { CorInfoType cit = ToCorInfoType(); _ASSERTE(IsStackNormalType(cit)); // Precondition. return CorInfoTypeStackNormalSize(cit); } // Is it a struct? (But don't include "native struct type"). bool IsStruct() const { intptr_t asInt = reinterpret_cast<intptr_t>(m_tp); return (asInt & 0x1) == 0x1 || (asInt == CORINFO_TYPE_SHIFTED_REFANY); } // Returns "true" iff represents a large (> INT64 size) struct. bool IsLargeStruct(CEEInfo* ceeInfo) const { intptr_t asInt = reinterpret_cast<intptr_t>(m_tp); #if defined(TARGET_AMD64) && !defined(UNIX_AMD64_ABI) if (asInt == CORINFO_TYPE_SHIFTED_REFANY) { return true; } #endif return (asInt & 0x3) == 0x3 || ((asInt & 0x3) == 0x2 && Size(ceeInfo) > sizeof(INT64)); } #ifdef _DEBUG bool MatchesWork(const InterpreterType it2, CEEInfo* info) const; bool Matches(const InterpreterType it2, CEEInfo* info) const { CONTRACTL { THROWS; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; return MatchesWork(it2, info) || it2.MatchesWork(*this, info); } #endif // _DEBUG }; #ifndef DACCESS_COMPILE // This class does whatever "global" (applicable to all executions after the first, as opposed to caching // within a single execution) we do. It is parameterized over the "Key" type (which is required to be an integral // type, to allow binary search), and the "Val" type of things cached. template<typename Key, typename Val> class InterpreterCache { public: InterpreterCache(); // Returns "false" if "k" is already present, otherwise "true". Requires that "v" == current mapping // if "k" is already present. bool AddItem(Key k, Val v); bool GetItem(Key k, Val& v); private: struct KeyValPair { Key m_key; Val m_val; }; // This is kept ordered by m_iloffset, to enable binary search. KeyValPair* m_pairs; unsigned short m_allocSize; unsigned short m_count; static const unsigned InitSize = 8; void EnsureCanInsert(); #ifdef _DEBUG static void AddAllocBytes(unsigned bytes); #endif // _DEBUG }; #ifdef _DEBUG enum CachedItemKind { CIK_Undefined, CIK_CallSite, CIK_StaticField, CIK_InstanceField, CIK_ClassHandle, }; #endif // _DEBUG struct StaticFieldCacheEntry { void* m_srcPtr; UINT m_sz; InterpreterType m_it; StaticFieldCacheEntry(void* srcPtr, UINT sz, InterpreterType it) : m_srcPtr(srcPtr), m_sz(sz), m_it(it) {} #ifdef _DEBUG bool operator==(const StaticFieldCacheEntry& entry) const { return m_srcPtr == entry.m_srcPtr && m_sz == entry.m_sz && m_it == entry.m_it; } #endif // _DEBUG }; // "small" part of CORINFO_SIG_INFO, sufficient for the interpreter to call the method so decribed struct CORINFO_SIG_INFO_SMALL { CORINFO_CLASS_HANDLE retTypeClass; // if the return type is a value class, this is its handle (enums are normalized) unsigned numArgs : 16; CorInfoCallConv callConv: 8; CorInfoType retType : 8; CorInfoCallConv getCallConv() { return CorInfoCallConv((callConv & CORINFO_CALLCONV_MASK)); } bool hasThis() { return ((callConv & CORINFO_CALLCONV_HASTHIS) != 0); } bool hasExplicitThis() { return ((callConv & CORINFO_CALLCONV_EXPLICITTHIS) != 0); } unsigned totalILArgs() { return (numArgs + hasThis()); } bool isVarArg() { return ((getCallConv() == CORINFO_CALLCONV_VARARG) || (getCallConv() == CORINFO_CALLCONV_NATIVEVARARG)); } bool hasTypeArg() { return ((callConv & CORINFO_CALLCONV_PARAMTYPE) != 0); } #ifdef _DEBUG bool operator==(const CORINFO_SIG_INFO_SMALL& csis) const { return retTypeClass == csis.retTypeClass && numArgs == csis.numArgs && callConv == csis.callConv && retType == csis.retType; } #endif // _DEBUG }; struct CallSiteCacheData { MethodDesc* m_pMD; CORINFO_SIG_INFO_SMALL m_sigInfo; CallSiteCacheData(MethodDesc* pMD, const CORINFO_SIG_INFO_SMALL& sigInfo) : m_pMD(pMD), m_sigInfo(sigInfo) {} #ifdef _DEBUG bool operator==(const CallSiteCacheData& cscd) const { return m_pMD == cscd.m_pMD && m_sigInfo == cscd.m_sigInfo; } #endif // _DEBUG }; struct CachedItem { #ifdef _DEBUG CachedItemKind m_tag; #endif // _DEBUG union { // m_tag == CIK_CallSite CallSiteCacheData* m_callSiteInfo; // m_tag == CIK_StaticField StaticFieldCacheEntry* m_staticFieldAddr; // m_tag == CIK_InstanceField FieldDesc* m_instanceField; // m_tag == CIT_ClassHandle CORINFO_CLASS_HANDLE m_clsHnd; } m_value; CachedItem() #ifdef _DEBUG : m_tag(CIK_Undefined) #endif {} #ifdef _DEBUG bool operator==(const CachedItem& ci) { if (m_tag != ci.m_tag) return false; switch (m_tag) { case CIK_CallSite: return *m_value.m_callSiteInfo == *ci.m_value.m_callSiteInfo; case CIK_StaticField: return *m_value.m_staticFieldAddr == *ci.m_value.m_staticFieldAddr; case CIK_InstanceField: return m_value.m_instanceField == ci.m_value.m_instanceField; case CIK_ClassHandle: return m_value.m_clsHnd == ci.m_value.m_clsHnd; default: return true; } } #endif CachedItem(CallSiteCacheData* callSiteInfo) #ifdef _DEBUG : m_tag(CIK_CallSite) #endif { m_value.m_callSiteInfo = callSiteInfo; } CachedItem(StaticFieldCacheEntry* staticFieldAddr) #ifdef _DEBUG : m_tag(CIK_StaticField) #endif { m_value.m_staticFieldAddr = staticFieldAddr; } CachedItem(FieldDesc* instanceField) #ifdef _DEBUG : m_tag(CIK_InstanceField) #endif { m_value.m_instanceField = instanceField; } CachedItem(CORINFO_CLASS_HANDLE m_clsHnd) #ifdef _DEBUG : m_tag(CIK_ClassHandle) #endif { m_value.m_clsHnd = m_clsHnd; } }; const char* eeGetMethodFullName(CEEInfo* info, CORINFO_METHOD_HANDLE hnd, const char** clsName = NULL); // The per-InterpMethodInfo cache may map generic instantiation information to the // cache for the current instantitation; when we find the right one the first time we copy it // into here, so we only have to do the instantiation->cache lookup once. typedef InterpreterCache<unsigned, CachedItem> ILOffsetToItemCache; typedef InterpreterCache<size_t, ILOffsetToItemCache*> GenericContextToInnerCache; #endif // DACCESS_COMPILE // This is the information that the intepreter stub provides to the // interpreter about the method being interpreted. struct InterpreterMethodInfo { #if INTERP_PROFILE || defined(_DEBUG) const char* m_clsName; const char* m_methName; #endif // Stub num for the current method under interpretation. int m_stubNum; // The method this info is relevant to. CORINFO_METHOD_HANDLE m_method; // The module containing the method. CORINFO_MODULE_HANDLE m_module; // Code pointer, size, and max stack usage. BYTE* m_ILCode; BYTE* m_ILCodeEnd; // One byte past the last byte of IL. IL Code Size = m_ILCodeEnd - m_ILCode. // The CLR transforms delegate constructors, and may add up to this many // extra arguments. This amount will be added to the IL's reported MaxStack to // get the "maxStack" value below, so we can use a uniform calling convention for // "DoCall". unsigned m_maxStack; unsigned m_ehClauseCount; // Used to implement arglist, an index into the ilArgs array where the argument pointed to is VA sig cookie. unsigned m_varArgHandleArgNum; // The number of arguments. unsigned short m_numArgs; // The number of local variables. unsigned short m_numLocals; enum Flags { // Is the first argument a "this" pointer? Flag_hasThisArg, // If "m_hasThisArg" is true, indicates whether the type of this is an object pointer // or a byref. Flag_thisArgIsObjPtr, // Is there a return buffer argument? Flag_hasRetBuffArg, // Is the method a var arg method Flag_isVarArg, // Is the last argument a generic type context? Flag_hasGenericsContextArg, // Does the type have generic args? Flag_typeHasGenericArgs, // Does the method have generic args? Flag_methHasGenericArgs, // Is the method a "dead simple" getter (one that just reads a field?) Flag_methIsDeadSimpleGetter, // We recognize two forms of dead simple getters, one for "opt" and one for "dbg". If it is // dead simple, is it dbg or opt? Flag_methIsDeadSimpleGetterIsDbgForm, Flag_Count, }; typedef UINT16 FlagGroup; // The bitmask for a set of InterpreterMethodInfo::Flags. FlagGroup m_flags; template<int Flg> FlagGroup GetFlagBit() { // This works as long as FlagGroup is "int" type. static_assert(sizeof(FlagGroup) * 8 >= Flag_Count, "error: bitset not large enough"); return (1 << Flg); } // Get and set the value of a flag. template<int Flg> bool GetFlag() { return (m_flags & GetFlagBit<Flg>()) != 0; } template<int Flg> void SetFlag(bool b) { if (b) m_flags |= GetFlagBit<Flg>(); else m_flags &= (~GetFlagBit<Flg>()); } // This structure describes a local: its type and its offset. struct LocalDesc { InterpreterType m_typeStackNormal; InterpreterType m_type; unsigned m_offset; }; // This structure describes an argument. Much like a LocalDesc, but // "m_nativeOffset" contains the offset if the argument was passed using the system's native calling convention // (e.g., the calling convention for a JIT -> Interpreter call) whereas "m_directOffset" describes arguments passed // via a direct Interpreter -> Interpreter call. struct ArgDesc { InterpreterType m_typeStackNormal; InterpreterType m_type; short m_nativeOffset; short m_directOffset; }; // This is an array of size at least "m_numArgs", such that entry "i" describes the "i'th" // arg in the "m_ilArgs" array passed to the intepreter: that is, the ArgDesc contains the type, stack-normal type, // and offset in the "m_ilArgs" array of that argument. In addition, has extra entries if "m_hasGenericsContextArg" // and/or "m_hasRetBuffArg" are true, giving the offset of those arguments -- the offsets of those arguments // are in that order in the array. (The corresponding types should be NativeInt.) ArgDesc* m_argDescs; // This is an array of size "m_numLocals", such that entry "i" describes the "i'th" // local : that is, the LocalDesc contains the type, stack-normal type, and, if the type // is a large struct type, the offset in the local variable large-struct memory array. LocalDesc* m_localDescs; // A bit map, with 1 bit per local, indicating whether it contains a pinning reference. char* m_localIsPinningRefBits; unsigned m_largeStructLocalSize; unsigned LocalMemSize() { return m_largeStructLocalSize + m_numLocals * sizeof(INT64); } // I will probably need more information about the return value, but for now... CorInfoType m_returnType; // The number of times this method has been interpreted. unsigned int m_invocations; #if INTERP_PROFILE UINT64 m_totIlInstructionsExeced; unsigned m_maxIlInstructionsExeced; void RecordExecInstrs(unsigned instrs) { m_totIlInstructionsExeced += instrs; if (instrs > m_maxIlInstructionsExeced) { m_maxIlInstructionsExeced = instrs; } } #endif // #ifndef DACCESS_COMPILE // Caching information. Currently the only thing we cache is saved formats of MethodDescCallSites // at call instructions. // We use a "void*", because the actual type depends on the whether the method has // a dynamic generics context. If so, this is a cache from the generic parameter to an // ILoffset->item cache; if not, it's a the ILoffset->item cache directly. void* m_methodCache; // #endif // DACCESS_COMPILE InterpreterMethodInfo(CEEInfo* comp, CORINFO_METHOD_INFO* methInfo); void InitArgInfo(CEEInfo* comp, CORINFO_METHOD_INFO* methInfo, short* argOffsets_); void AllocPinningBitsIfNeeded(); void SetPinningBit(unsigned locNum); bool GetPinningBit(unsigned locNum); CORINFO_CONTEXT_HANDLE GetPreciseGenericsContext(Object* thisArg, void* genericsCtxtArg); #ifndef DACCESS_COMPILE // Gets the proper cache for a call to a method with the current InterpreterMethodInfo, with the given // "thisArg" and "genericsCtxtArg". If "alloc" is true, will allocate the cache if necessary. ILOffsetToItemCache* GetCacheForCall(Object* thisArg, void* genericsCtxtArg, bool alloc = false); #endif // DACCESS_COMPILE ~InterpreterMethodInfo(); }; // Expose some protected methods of CEEInfo. class InterpreterCEEInfo: public CEEInfo { CEEJitInfo m_jitInfo; public: InterpreterCEEInfo(CORINFO_METHOD_HANDLE meth): CEEInfo((MethodDesc*)meth), m_jitInfo((MethodDesc*)meth, NULL, NULL, CORJIT_FLAGS::CORJIT_FLAG_SPEED_OPT) { } // Certain methods are unimplemented by CEEInfo (they hit an assert). They are implemented by CEEJitInfo, yet // don't seem to require any of the CEEJitInfo state we can't provide. For those case, delegate to the "partial" // CEEJitInfo m_jitInfo. void addActiveDependency(CORINFO_MODULE_HANDLE moduleFrom,CORINFO_MODULE_HANDLE moduleTo) { m_jitInfo.addActiveDependency(moduleFrom, moduleTo); } }; extern INT64 F_CALL_CONV InterpretMethod(InterpreterMethodInfo* methInfo, BYTE* ilArgs, void* stubContext); extern float F_CALL_CONV InterpretMethodFloat(InterpreterMethodInfo* methInfo, BYTE* ilArgs, void* stubContext); extern double F_CALL_CONV InterpretMethodDouble(InterpreterMethodInfo* methInfo, BYTE* ilArgs, void* stubContext); class Interpreter { friend INT64 F_CALL_CONV InterpretMethod(InterpreterMethodInfo* methInfo, BYTE* ilArgs, void* stubContext); friend float F_CALL_CONV InterpretMethodFloat(InterpreterMethodInfo* methInfo, BYTE* ilArgs, void* stubContext); friend double F_CALL_CONV InterpretMethodDouble(InterpreterMethodInfo* methInfo, BYTE* ilArgs, void* stubContext); // This will be inlined into the bodies of the methods above static inline ARG_SLOT InterpretMethodBody(InterpreterMethodInfo* interpMethInfo, bool directCall, BYTE* ilArgs, void* stubContext); // The local frame size of the method being interpreted. static size_t GetFrameSize(InterpreterMethodInfo* interpMethInfo); // JIT the method if we've passed the threshold, or if "force" is true. static void JitMethodIfAppropriate(InterpreterMethodInfo* interpMethInfo, bool force = false); friend class InterpreterFrame; public: // Return an interpreter stub for the given method. That is, a stub that transforms the arguments from the native // calling convention to the interpreter convention, and provides the method descriptor, then calls the interpreter. // If "jmpCall" setting is true, then "ppInterpreterMethodInfo" must be provided and the GenerateInterpreterStub // will NOT generate a stub. Instead it will provide a MethodInfo that is initialized correctly after computing // arg descs. static CorJitResult GenerateInterpreterStub(CEEInfo* comp, CORINFO_METHOD_INFO* info, /*OUT*/ BYTE **nativeEntry, /*OUT*/ ULONG *nativeSizeOfCode, InterpreterMethodInfo** ppInterpMethodInfo = NULL, bool jmpCall = false); // If "addr" is the start address of an interpreter stub, return the corresponding MethodDesc*, // else "NULL". static class MethodDesc* InterpretationStubToMethodInfo(PCODE addr); // A value to indicate that the cache has not been initialized (to distinguish it from NULL -- // we've looked and it doesn't yet have a cache.) #define UninitExecCache reinterpret_cast<ILOffsetToItemCache*>(0x1) // The "frameMemory" should be a pointer to a locally-allocated memory block // whose size is sufficient to hold the m_localVarMemory, the operand stack, and the // operand type stack. Interpreter(InterpreterMethodInfo* methInfo_, bool directCall_, BYTE* ilArgs_, void* stubContext_, BYTE* frameMemory) : m_methInfo(methInfo_), m_interpCeeInfo(methInfo_->m_method), m_ILCodePtr(methInfo_->m_ILCode), m_directCall(directCall_), m_ilArgs(ilArgs_), m_stubContext(stubContext_), m_orOfPushedInterpreterTypes(0), m_largeStructOperandStack(NULL), m_largeStructOperandStackHt(0), m_largeStructOperandStackAllocSize(0), m_curStackHt(0), m_leaveInfoStack(), m_filterNextScan(0), m_filterHandlerOffset(0), m_filterExcILOffset(0), m_inFlightException(NULL), m_thisArg(NULL), #ifdef USE_CHECKED_OBJECTREFS m_retBufArg(NULL), // Initialize to NULL so we can safely declare protected. #endif // USE_CHECKED_OBJECTREFS m_genericsCtxtArg(NULL), m_securityObject((Object*)NULL), m_args(NULL), m_argsSize(0), m_callThisArg(NULL), m_structRetValITPtr(NULL), #ifndef DACCESS_COMPILE // Means "uninitialized" m_thisExecCache(UninitExecCache), #endif m_constrainedFlag(false), m_readonlyFlag(false), m_locAllocData(NULL), m_preciseGenericsContext(NULL), m_functionPointerStack(NULL) { // We must zero the locals. memset(frameMemory, 0, methInfo_->LocalMemSize() + sizeof(GSCookie)); // m_localVarMemory is below the fixed size slots, above the large struct slots. m_localVarMemory = frameMemory + methInfo_->m_largeStructLocalSize + sizeof(GSCookie); m_gsCookieAddr = (GSCookie*) (m_localVarMemory - sizeof(GSCookie)); // Having zeroed, for large struct locals, we must initialize the fixed-size local slot to point to the // corresponding large-struct local slot. for (unsigned i = 0; i < methInfo_->m_numLocals; i++) { if (methInfo_->m_localDescs[i].m_type.IsLargeStruct(&m_interpCeeInfo)) { void* structPtr = ArgSlotEndianessFixup(reinterpret_cast<ARG_SLOT*>(FixedSizeLocalSlot(i)), sizeof(void**)); *reinterpret_cast<void**>(structPtr) = LargeStructLocalSlot(i); } } frameMemory += methInfo_->LocalMemSize(); frameMemory += sizeof(GSCookie); #define COMBINE_OPSTACK_VAL_TYPE 0 #if COMBINE_OPSTACK_VAL_TYPE m_operandStackX = reinterpret_cast<OpStackValAndType*>(frameMemory); frameMemory += (methInfo_->m_maxStack * sizeof(OpStackValAndType)); #else m_operandStack = reinterpret_cast<INT64*>(frameMemory); frameMemory += (methInfo_->m_maxStack * sizeof(INT64)); m_operandStackTypes = reinterpret_cast<InterpreterType*>(frameMemory); #endif // If we have a "this" arg, save it in case we need it later. (So we can // reliably get it even if the IL updates arg 0...) if (m_methInfo->GetFlag<InterpreterMethodInfo::Flag_hasThisArg>()) { m_thisArg = *reinterpret_cast<Object**>(GetArgAddr(0)); } unsigned extraArgInd = methInfo_->m_numArgs - 1; // We do these in the *reverse* of the order they appear in the array, so that we can conditionally process // the ones that are used. if (m_methInfo->GetFlag<InterpreterMethodInfo::Flag_hasGenericsContextArg>()) { m_genericsCtxtArg = *reinterpret_cast<Object**>(GetArgAddr(extraArgInd)); extraArgInd--; } if (m_methInfo->GetFlag<InterpreterMethodInfo::Flag_isVarArg>()) { extraArgInd--; } if (m_methInfo->GetFlag<InterpreterMethodInfo::Flag_hasRetBuffArg>()) { m_retBufArg = *reinterpret_cast<void**>(GetArgAddr(extraArgInd)); extraArgInd--; } } ~Interpreter() { if (m_largeStructOperandStack != NULL) { delete[] m_largeStructOperandStack; } if (m_locAllocData != NULL) { delete m_locAllocData; } if (m_functionPointerStack != NULL) { delete[] m_functionPointerStack; } } // Called during EE startup to initialize locks and other generic resources. static void Initialize(); // Called during stub generation to initialize compiler-specific resources. static void InitializeCompilerStatics(CEEInfo* info); // Called during EE shutdown to destroy locks and release generic resources. static void Terminate(); // Returns true iff "stackPtr" can only be in younger frames than "this". (On a downwards- // growing stack, it is less than the smallest local address of "this".) bool IsInCalleesFrames(void* stackPtr); MethodDesc* GetMethodDesc() { return reinterpret_cast<MethodDesc*>(m_methInfo->m_method); } #if INTERP_ILSTUBS void* GetStubContext() { return m_stubContext; } #endif OBJECTREF* GetAddressOfSecurityObject() { return &m_securityObject; } void* GetParamTypeArg() { return m_genericsCtxtArg; } private: // Architecture-dependent helpers. inline static unsigned short NumberOfIntegerRegArgs(); // Wrapper for ExecuteMethod to do a O(1) alloca when performing a jmpCall and normal calls. If doJmpCall is true, this method also resolves the call token into pResolvedToken. static ARG_SLOT ExecuteMethodWrapper(struct InterpreterMethodInfo* interpMethInfo, bool directCall, BYTE* ilArgs, void* stubContext, bool* pDoJmpCall, CORINFO_RESOLVED_TOKEN* pResolvedCallToken); // Execute the current method, and set *retVal to the return value, if any. void ExecuteMethod(ARG_SLOT* retVal, bool* pDoJmpCall, unsigned* pJumpCallToken); // Fetches the monitor for static methods by asking cee info. Returns the monitor // object. AwareLock* GetMonitorForStaticMethod(); // Synchronized methods have to call monitor enter and exit at the entry and exits of the // method. void DoMonitorEnterWork(); void DoMonitorExitWork(); // Determines if the current exception is handled by the current method. If so, // returns true and sets the interpreter state to start executing in the appropriate handler. bool MethodHandlesException(OBJECTREF orThrowable); // Assumes that "ilCode" is the first instruction in a method, whose code is of size "codeSize". // Returns "false" if this method has no loops; if it returns "true", it might have a loop. static bool MethodMayHaveLoop(BYTE* ilCode, unsigned codeSize); // Do anything that needs to be done on a backwards branch (e.g., GC poll). // Assumes that "offset" is the delta between the current code pointer and the post-branch pointer; // obviously, it will be negative. void BackwardsBranchActions(int offset); // Expects "interp0" to be the address of the interpreter object being scanned. static void GCScanRoots(promote_func* pf, ScanContext* sc, void* interp0); // The above calls this instance method. void GCScanRoots(promote_func* pf, ScanContext* sc); // Scan the root at "loc", whose type is "it", using "pf" and "sc". void GCScanRootAtLoc(Object** loc, InterpreterType it, promote_func* pf, ScanContext* sc, bool pinningRef = false); // Scan the root at "loc", whose type is the value class "valueCls", using "pf" and "sc". void GCScanValueClassRootAtLoc(Object** loc, CORINFO_CLASS_HANDLE valueClsHnd, promote_func* pf, ScanContext* sc); // Asserts that "addr" is the start of the interpretation stub for "md". Records this in a table, // to satisfy later calls to "InterpretationStubToMethodInfo." static void RecordInterpreterStubForMethodDesc(CORINFO_METHOD_HANDLE md, void* addr); struct ArgState { unsigned short numRegArgs; unsigned short numFPRegArgSlots; unsigned fpArgsUsed; // Bit per single-precision fp arg accounted for. short callerArgStackSlots; short* argOffsets; enum ArgRegStatus { ARS_IntReg, ARS_FloatReg, ARS_NotReg }; ArgRegStatus* argIsReg; ArgState(unsigned totalArgs) : numRegArgs(0), numFPRegArgSlots(0), fpArgsUsed(0), callerArgStackSlots(0), argOffsets(new short[totalArgs]), argIsReg(new ArgRegStatus[totalArgs]) { for (unsigned i = 0; i < totalArgs; i++) { argIsReg[i] = ARS_NotReg; argOffsets[i] = 0; } } #if defined(HOST_ARM) static const int MaxNumFPRegArgSlots = 16; #elif defined(HOST_ARM64) static const int MaxNumFPRegArgSlots = 8; #elif defined(HOST_AMD64) #if defined(UNIX_AMD64_ABI) static const int MaxNumFPRegArgSlots = 8; #else static const int MaxNumFPRegArgSlots = 4; #endif #endif ~ArgState() { delete[] argOffsets; delete[] argIsReg; } void AddArg(unsigned canonIndex, short numSlots = 1, bool noReg = false, bool twoSlotAlign = false); // By this call, argument "canonIndex" is declared to be a floating point argument, taking the given # // of slots. Important that this be called in argument order. void AddFPArg(unsigned canonIndex, unsigned short numSlots, bool doubleAlign); #if defined(HOST_AMD64) // We have a special function for AMD64 because both integer/float registers overlap. However, all // callers are expected to call AddArg/AddFPArg directly. void AddArgAmd64(unsigned canonIndex, unsigned short numSlots, bool isFloatingType); #endif }; typedef MapSHash<void*, CORINFO_METHOD_HANDLE> AddrToMDMap; static AddrToMDMap* s_addrToMDMap; static AddrToMDMap* GetAddrToMdMap(); // In debug, we map to a pair, containing the Thread that inserted it, so we can assert that any given thread only // inserts one stub for a CORINFO_METHOD_HANDLE. struct MethInfo { InterpreterMethodInfo* m_info; #ifdef _DEBUG Thread* m_thread; #endif // _DEBUG }; typedef MapSHash<CORINFO_METHOD_HANDLE, MethInfo> MethodHandleToInterpMethInfoPtrMap; static MethodHandleToInterpMethInfoPtrMap* s_methodHandleToInterpMethInfoPtrMap; static MethodHandleToInterpMethInfoPtrMap* GetMethodHandleToInterpMethInfoPtrMap(); static InterpreterMethodInfo* RecordInterpreterMethodInfoForMethodHandle(CORINFO_METHOD_HANDLE md, InterpreterMethodInfo* methInfo); static InterpreterMethodInfo* MethodHandleToInterpreterMethInfoPtr(CORINFO_METHOD_HANDLE md); public: static unsigned s_interpreterStubNum; private: unsigned CurOffset() { _ASSERTE(m_methInfo->m_ILCode <= m_ILCodePtr && m_ILCodePtr < m_methInfo->m_ILCodeEnd); unsigned res = static_cast<unsigned>(m_ILCodePtr - m_methInfo->m_ILCode); return res; } // We've computed a branch target. Is the target in range? If not, throw an InvalidProgramException. // Otherwise, execute the branch by changing m_ILCodePtr. void ExecuteBranch(BYTE* ilTargetPtr) { if (m_methInfo->m_ILCode <= ilTargetPtr && ilTargetPtr < m_methInfo->m_ILCodeEnd) { m_ILCodePtr = ilTargetPtr; } else { COMPlusThrow(kInvalidProgramException); } } // Private fields: // InterpreterMethodInfo* m_methInfo; InterpreterCEEInfo m_interpCeeInfo; BYTE* m_ILCodePtr; bool m_directCall; BYTE* m_ilArgs; __forceinline InterpreterType GetArgType(unsigned argNum) { return m_methInfo->m_argDescs[argNum].m_type; } __forceinline InterpreterType GetArgTypeNormal(unsigned argNum) { return m_methInfo->m_argDescs[argNum].m_typeStackNormal; } __forceinline BYTE* GetArgAddr(unsigned argNum) { if (!m_directCall) { #if defined(HOST_AMD64) && !defined(UNIX_AMD64_ABI) // In AMD64, a reference to the struct is passed if its size exceeds the word size. // Dereference the arg to get to the ref of the struct. if (GetArgType(argNum).IsLargeStruct(&m_interpCeeInfo)) { return *reinterpret_cast<BYTE**>(&m_ilArgs[m_methInfo->m_argDescs[argNum].m_nativeOffset]); } #endif return &m_ilArgs[m_methInfo->m_argDescs[argNum].m_nativeOffset]; } else { if (GetArgType(argNum).IsLargeStruct(&m_interpCeeInfo)) { return *reinterpret_cast<BYTE**>(&m_ilArgs[m_methInfo->m_argDescs[argNum].m_directOffset]); } else { return &m_ilArgs[m_methInfo->m_argDescs[argNum].m_directOffset]; } } } __forceinline MethodTable* GetMethodTableFromClsHnd(CORINFO_CLASS_HANDLE hnd) { TypeHandle th(hnd); return th.GetMethodTable(); } #ifdef FEATURE_HFA __forceinline BYTE* GetHFARetBuffAddr(unsigned sz) { // Round up to a double boundary: sz = ((sz + sizeof(double) - 1) / sizeof(double)) * sizeof(double); // We rely on the interpreter stub to have pushed "sz" bytes on its stack frame, // below m_ilArgs; return m_ilArgs - sz; } #endif // FEATURE_HFA void* m_stubContext; // Address of the GSCookie value in the current method's frame. GSCookie* m_gsCookieAddr; BYTE* GetFrameBase() { return (m_localVarMemory - sizeof(GSCookie) - m_methInfo->m_largeStructLocalSize); } // m_localVarMemory points to the boundary between the fixed-size slots for the locals // (positive offsets), and the full-sized slots for large struct locals (negative offsets). BYTE* m_localVarMemory; INT64* FixedSizeLocalSlot(unsigned locNum) { return reinterpret_cast<INT64*>(m_localVarMemory) + locNum; } BYTE* LargeStructLocalSlot(unsigned locNum) { BYTE* base = GetFrameBase(); BYTE* addr = base + m_methInfo->m_localDescs[locNum].m_offset; _ASSERTE(IsInLargeStructLocalArea(addr)); return addr; } bool IsInLargeStructLocalArea(void* addr) { void* base = GetFrameBase(); return (base <= addr) && (addr < (static_cast<void*>(m_localVarMemory - sizeof(GSCookie)))); } bool IsInLocalArea(void* addr) { void* base = GetFrameBase(); return (base <= addr) && (addr < static_cast<void*>(reinterpret_cast<INT64*>(m_localVarMemory) + m_methInfo->m_numLocals)); } // Ensures that the operand stack contains no pointers to large struct local slots (by // copying the values out to locations allocated on the large struct stack. void OpStackNormalize(); // The defining property of this word is: if the bottom two bits are not 0x3, then the current operand stack contains no pointers // to large-struct slots for locals. Operationally, we achieve this by taking "OR" of the interpreter types of local variables that have been loaded onto the // operand stack -- if any have been large structs, they will have 0x3 as the low order bits of their interpreter type, and this will be // "sticky." We may sometimes determine that no large struct local pointers are currently on the stack, and reset this word to zero. size_t m_orOfPushedInterpreterTypes; #if COMBINE_OPSTACK_VAL_TYPE struct OpStackValAndType { INT64 m_val; InterpreterType m_type; INT32 m_pad; }; OpStackValAndType* m_operandStackX; #else INT64* m_operandStack; #endif template<typename T> __forceinline T OpStackGet(unsigned ind) { return *OpStackGetAddr<T>(ind); } template<typename T> __forceinline void OpStackSet(unsigned ind, T val) { *OpStackGetAddr<T>(ind) = val; } #if COMBINE_OPSTACK_VAL_TYPE template<typename T> __forceinline T* OpStackGetAddr(unsigned ind) { return reinterpret_cast<T*>(ArgSlotEndianessFixup(reinterpret_cast<ARG_SLOT*>(&m_operandStackX[ind].m_val), sizeof(T))); } __forceinline void* OpStackGetAddr(unsigned ind, size_t sz) { return ArgSlotEndianessFixup(reinterpret_cast<ARG_SLOT*>(&m_operandStackX[ind].m_val), sz); } #else template<typename T> __forceinline T* OpStackGetAddr(unsigned ind) { return reinterpret_cast<T*>(ArgSlotEndianessFixup(reinterpret_cast<ARG_SLOT*>(&m_operandStack[ind]), sizeof(T))); } __forceinline void* OpStackGetAddr(unsigned ind, size_t sz) { return ArgSlotEndianessFixup(reinterpret_cast<ARG_SLOT*>(&m_operandStack[ind]), sz); } #endif __forceinline INT64 GetSmallStructValue(void* src, size_t sz) { _ASSERTE(sz <= sizeof(INT64)); INT64 ret = 0; memcpy(ArgSlotEndianessFixup(reinterpret_cast<ARG_SLOT*>(&ret), sz), src, sz); return ret; } BYTE* m_largeStructOperandStack; size_t m_largeStructOperandStackHt; size_t m_largeStructOperandStackAllocSize; // Allocate "sz" bytes on the large struct operand stack, and return a pointer to where // the structure should be copied. void* LargeStructOperandStackPush(size_t sz); // Deallocate "sz" bytes from the large struct operand stack, unless the corresponding // operand stack value "fromAddr" is a pointer to a local variable. void LargeStructOperandStackPop(size_t sz, void* fromAddr); // Ensures that we can push a struct of size "sz" on the large struct operand stack. void LargeStructOperandStackEnsureCanPush(size_t sz); #ifdef _DEBUG // Returns "true" iff the sum of sizes of large structures on the operand stack // equals "m_largeStructOperandStackHt", which should be an invariant. bool LargeStructStackHeightIsValid(); #endif // _DEBUG // Returns "true" iff the "cit" is 'considered' a valid pointer type for the // architecture. For ex: nativeint/byref and for amd64 longs with loose rules. bool IsValidPointerType(CorInfoType cit); #if !COMBINE_OPSTACK_VAL_TYPE InterpreterType* m_operandStackTypes; #endif #if COMBINE_OPSTACK_VAL_TYPE #if USE_MACRO_FOR_OPSTACKACCESS #define OpStackTypeGet(ind) m_operandStackX[ind].m_type #define OpStackTypeSet(ind, it) m_operandStackX[ind].m_type = it #else __forceinline InterpreterType OpStackTypeGet(unsigned ind) { return m_operandStackX[ind].m_type; } __forceinline void OpStackTypeSet(unsigned ind, InterpreterType it) { _ASSERTE(IsStackNormalType(it.ToCorInfoType())); m_operandStackX[ind].m_type = it; } #endif #else __forceinline InterpreterType OpStackTypeGet(unsigned ind) { return m_operandStackTypes[ind]; } __forceinline void OpStackTypeSet(unsigned ind, InterpreterType it) { _ASSERTE(IsStackNormalType(it.ToCorInfoType())); m_operandStackTypes[ind] = it; } #endif unsigned m_curStackHt; // These are used in searching for finally clauses when we 'leave' a try block: struct LeaveInfo { unsigned m_offset; // The offset of "leave" instructions in try blocks whose finally blocks are being executed. BYTE* m_target; // The location the 'leave' was jumping to -- where execution should resume after all finally's have been executed. unsigned m_nextEHIndex; // The index in the EH table at which the search for the next finally for "lastLeaveOffset" should resume. LeaveInfo(unsigned offset = 0, BYTE* target = NULL) : m_offset(offset), m_target(target), m_nextEHIndex(0) {} }; // This is a stack of the currently in-force "leaves." (Multiple leave's can be being processed when a try-finally occurs // within a finally). Stack<LeaveInfo> m_leaveInfoStack; // Used to track the next filter to scan in case the current // filter doesn't handle the exception. unsigned m_filterNextScan; // Used to record the handler offset for the current filter so it can be used during endfilter. unsigned m_filterHandlerOffset; // The actual offset at which the exception occurred for a filter that might possibly handle it. unsigned m_filterExcILOffset; // This is the exception to rethrow upon exiting the last finally. Object* m_inFlightException; // This must be scanned by GC. // Storing "this" and "typeCtxt" args if necessary. Object* m_thisArg; // This must be scanned by GC. void* m_retBufArg; // This must be scanned by GC: // if the caller is JITted, o.f = Foo(), for o.f a value type, retBuf may be ref o.f. void* m_genericsCtxtArg; // Acquired variable for synchronized methods. unsigned char m_monAcquired; // Holds the security object, for frames that require it. OBJECTREF m_securityObject; ARG_SLOT* m_args; InterpreterType* m_argTypes; unsigned m_argsSize; void* m_callThisArg; // If "m_structRetValITPtr" is non-NULL, then "*m_structRetValITPtr" represents a struct type, and // "m_structRetValTempSpace" is a pointer to a value of that struct type, which must be scanned during GC. InterpreterType* m_structRetValITPtr; void* m_structRetValTempSpace; #ifdef DACCESS_COMPILE void* m_thisExecCache; #else // DACCESS_COMPILE // The proper cache for the current method execution (or else UninitExecCache). ILOffsetToItemCache* m_thisExecCache; // Retrieve the ILoffset->Item cache for the generic instantiation (if any) of the // currently-executing method. If "alloc" is true, allocate one if its not there. ILOffsetToItemCache* GetThisExecCache(bool alloc) { if (m_thisExecCache == UninitExecCache || (m_thisExecCache == NULL && alloc)) { m_thisExecCache = m_methInfo->GetCacheForCall(m_thisArg, m_genericsCtxtArg, alloc); } _ASSERTE(!alloc || m_thisExecCache != NULL); return m_thisExecCache; } // Cache that a call at "iloffset" has the given CallSiteCacheData "callInfo". void CacheCallInfo(unsigned iloffset, CallSiteCacheData* callInfo); // If there's a cached CORINFO_CALL_INFO for the call at the given IL offset, return it, else NULL. CallSiteCacheData* GetCachedCallInfo(unsigned iloffset); void CacheInstanceField(unsigned iloffset, FieldDesc* fld); FieldDesc* GetCachedInstanceField(unsigned iloffset); void CacheStaticField(unsigned iloffset, StaticFieldCacheEntry* pEntry); StaticFieldCacheEntry* GetCachedStaticField(unsigned iloffset); void CacheClassHandle(unsigned ilOffset, CORINFO_CLASS_HANDLE clsHnd); CORINFO_CLASS_HANDLE GetCachedClassHandle(unsigned iloffset); #endif // DACCESS_COMPILE #if INTERP_ILCYCLE_PROFILE // Cycles we want to delete from the current instructions cycle count; e.g., // cycles spent in a callee. unsigned __int64 m_exemptCycles; unsigned __int64 m_startCycles; unsigned short m_instr; void UpdateCycleCount(); #endif // INTERP_ILCYCLE_PROFILE #ifdef _DEBUG // These collectively record all the interpreter method infos we've created. static InterpreterMethodInfo** s_interpMethInfos; static unsigned s_interpMethInfosAllocSize; static unsigned s_interpMethInfosCount; static void AddInterpMethInfo(InterpreterMethodInfo* methInfo); // Print any end-of-run summary information we've collected, and want // printed. // Both methods below require that "mi0" and "mi1" are actually "InterpreterMethodInfo*"s. // Returns -1, 0, or 1, depending on whether "mi0->m_invocations" is less than, // equal, or greater than "mi1->m_invocations.". static int _cdecl CompareMethInfosByInvocations(const void* mi0, const void* mi1); #if INTERP_PROFILE // Returns 1, 0, or -1, depending on whether "mi0->m_totIlInstructionsExeced" is less than, // equal, or greater than "mi1->m_totIlInstructionsExeced.". (Note that this enables a descending sort.) static int _cdecl CompareMethInfosByILInstrs(const void* mi0, const void* mi1); #endif // INTERP_PROFILE #endif // _DEBUG private: static ConfigDWORD s_PrintPostMortemFlag; public: static void PrintPostMortemData(); #if INTERP_TRACING private: // Returns a string name of the il operation at "ILCodePtr". static const char* ILOp(BYTE* ilCodePtr); static const char* ILOp1Byte(unsigned short ilInstrVal); static const char* ILOp2Byte(unsigned short ilInstrVal); // Prints a representation of the operand stack. void PrintOStack(); // Prints a representation of the arguments. void PrintArgs(); // Prints a representation of the locals. void PrintLocals(); // Helper functions for the above: // Print the value at ostack position "index". void PrintOStackValue(unsigned index); // Print the value of the argument number "argNum". void PrintArgValue(unsigned argNum); // Requires that "valAddr" point to a location containing a value of type // "cit", and prints that value. void PrintValue(InterpreterType cit, BYTE* valAddr); public: static inline FILE* GetLogFile(); private: static FILE* s_InterpreterLogFile; static ConfigDWORD s_DumpInterpreterStubsFlag; static ConfigDWORD s_TraceInterpreterEntriesFlag; static ConfigDWORD s_TraceInterpreterILFlag; static ConfigDWORD s_TraceInterpreterOstackFlag; static ConfigDWORD s_TraceInterpreterVerboseFlag; static ConfigDWORD s_TraceInterpreterJITTransitionFlag; static ConfigDWORD s_InterpreterStubMin; static ConfigDWORD s_InterpreterStubMax; // The total number of method invocations. static LONG s_totalInvocations; // The total number of calls made by interpreted code. static LONG s_totalInterpCalls; static LONG s_totalInterpCallsToGetters; static LONG s_totalInterpCallsToDeadSimpleGetters; static LONG s_totalInterpCallsToDeadSimpleGettersShortCircuited; static LONG s_totalInterpCallsToSetters; static LONG s_totalInterpCallsToIntrinsics; static LONG s_totalInterpCallsToIntrinsicsUnhandled; enum ResolveTokenKind { RTK_Undefined, RTK_Constrained, RTK_NewObj, RTK_NewArr, RTK_LdToken, RTK_LdFtn, RTK_LdVirtFtn, RTK_SFldAddr, RTK_LdElem, RTK_Call, RTK_LdObj, RTK_StObj, RTK_CpObj, RTK_InitObj, RTK_IsInst, RTK_CastClass, RTK_MkRefAny, RTK_RefAnyVal, RTK_Sizeof, RTK_StElem, RTK_Box, RTK_Unbox, RTK_UnboxAny, RTK_LdFld, RTK_LdFldA, RTK_StFld, RTK_FindClass, RTK_CheckHandlesException, RTK_Count }; static const char* s_tokenResolutionKindNames[RTK_Count]; static LONG s_tokenResolutionOpportunities[RTK_Count]; static LONG s_tokenResolutionCalls[RTK_Count]; #endif // INTERP_TRACING #if INTERP_ILINSTR_PROFILE static unsigned short s_ILInstrCategories[512]; static int s_ILInstrExecs[256]; static int s_ILInstrExecsByCategory[512]; #if INTERP_ILCYCLE_PROFILE static unsigned __int64 s_ILInstrCyclesByCategory[512]; #endif // INTERP_ILCYCLE_PROFILE static const unsigned CountIlInstr2Byte = 0x22; static int s_ILInstr2ByteExecs[CountIlInstr2Byte]; #if INTERP_ILCYCLE_PROFILE static unsigned __int64 s_ILInstrCycles[512]; // XXX static unsigned __int64 s_callCycles; static unsigned s_calls; #endif // INTERP_ILCYCLE_PROFILE #endif // INTERP_ILINSTR_PROFILE // Non-debug-only statics. static ConfigMethodSet s_InterpretMeths; static ConfigMethodSet s_InterpretMethsExclude; static ConfigDWORD s_InterpretMethHashMin; static ConfigDWORD s_InterpretMethHashMax; static ConfigDWORD s_InterpreterJITThreshold; static ConfigDWORD s_InterpreterDoLoopMethodsFlag; static bool s_InterpreterDoLoopMethods; static ConfigDWORD s_InterpreterUseCachingFlag; static bool s_InterpreterUseCaching; static ConfigDWORD s_InterpreterLooseRulesFlag; static bool s_InterpreterLooseRules; static CrstExplicitInit s_methodCacheLock; static CrstExplicitInit s_interpStubToMDMapLock; // True iff a "constrained" prefix has preceded a call. bool m_constrainedFlag; // True iff a "volatile" prefixe precedes a memory reference. bool m_volatileFlag; // If there has been a "constrained" prefix, this is initialized // with the token of the constraint class. CORINFO_RESOLVED_TOKEN m_constrainedResolvedToken; // True iff a "readonly" prefix has preceded a ldelema. bool m_readonlyFlag; // Data structures related to localloc. class LocAllocData { typedef void* PVoid; unsigned m_locAllocSize; // The currently allocated # elements in m_locAllocs unsigned m_locAllocCurIdx; // Number of elements of m_locAllocs in use; 0 <= m_locAllocCurIdx < m_locAllocSize void** m_locAllocs; // Always non-null in a constructed LocAllocData. static const unsigned DefaultAllocs = 1; unsigned EnsureIdx() { if (m_locAllocCurIdx == m_locAllocSize) { unsigned newSize = m_locAllocSize * 2; void** newLocAllocs = new PVoid[newSize]; for (unsigned j = 0; j < m_locAllocCurIdx; j++) { newLocAllocs[j] = m_locAllocs[j]; } m_locAllocSize = newSize; delete[] m_locAllocs; m_locAllocs = newLocAllocs; } return m_locAllocCurIdx++; // Note that we're returning the value before post-increment. } public: LocAllocData() : m_locAllocSize(DefaultAllocs), m_locAllocCurIdx(0) { m_locAllocs = new PVoid[DefaultAllocs]; memset(m_locAllocs, 0, DefaultAllocs * sizeof(void*)); } void* Alloc(NativeUInt sz) { unsigned idx = EnsureIdx(); void* res = new char[sz]; // We only *have* to do this if initlocals is set, but no harm in always doing it. memset(res, 0, sz); m_locAllocs[idx] = res; return res; } ~LocAllocData() { if (m_locAllocs != NULL) { for (unsigned i = 0; i < m_locAllocCurIdx; i++) { delete[] reinterpret_cast<char*>(m_locAllocs[i]); } } delete[] m_locAllocs; } }; LocAllocData* m_locAllocData; LocAllocData* GetLocAllocData() { if (m_locAllocData == NULL) { m_locAllocData = new LocAllocData(); } return m_locAllocData; } // Search the current method's exception table, starting at "leaveEHIndex", for the first finally clause // for a try block that covers "lastLeaveOffset". If one is found, sets m_ILCodePtr to the start of that // finally clause, updates "leaveEHIndex" to be the next index after the found clause in the exception // table, and returns true. Otherwise, if no applicable finally clause is found, returns false. bool SearchForCoveringFinally(); void LdIcon(INT32 c); void LdLcon(INT64 c); void LdR4con(INT32 c); void LdR8con(INT64 c); void LdArg(int argNum); void LdArgA(int argNum); void StArg(int argNum); __forceinline void LdLoc(int locNum); void LdLocA(int locNum); __forceinline void StLoc(int locNum); // Requires that "*addr" contain a value of type "tp"; reads that value and // pushes it on the operand stack. __forceinline void LdFromMemAddr(void* addr, InterpreterType tp); // Requires that "addr" is the address of a local var or argument location. // Pops the value on the operand stack, assumed to be of the given "tp", and stores // in "*addr". __forceinline void StToLocalMemAddr(void* addr, InterpreterType tp); void LdNull(); // This requires that the width of "T" is at least 4 bytes. template<typename T, CorInfoType cit> void LdInd(); // This requires that the width of "T" is less than 4 bytes (and loads it as an INT32). template<typename T, bool isUnsigned> void LdIndShort(); void LdIndFloat(); // Use this for non-object-ref types, and StInd_Ref for object refs. template<typename T> void StInd(); void StInd_Ref(); // Load/store instance/static fields. // If non-NULL, we've determined the field to be loaded by other means (e.g., we've identified a // "dead simple" property getter). In this case, use this FieldDesc*, otherwise, look up via token // or cache. void LdFld(FieldDesc* fld = NULL); void LdFldA(); void LdSFld(); void LdSFldA(); void StFld(); void StSFld(); // Helper method used by the static field methods above. // Requires that the code stream be pointing to a LDSFLD, LDSFLDA, or STSFLD. // The "accessFlgs" variable should indicate which, by which of the CORINFO_ACCESS_GET, // CORINFO_ACCESS_GET, and CORINFO_ACCESS_ADDRESS bits are set. // Sets *pStaticFieldAddr, which must be a pointer to memory protected as a byref) to the address of the static field, // sets *pit to the InterpreterType of the field, // sets *pFldSize to the size of the field, and sets *pManagedMem to true iff the address is in managed memory (this is // false only if the static variable is an "RVA"). (Increments the m_ILCodePtr of 'this' by 5, the // assumed size of all the listed instructions. __forceinline void StaticFldAddr(CORINFO_ACCESS_FLAGS accessFlgs, /*out (byref)*/void** pStaticFieldAddr, /*out*/InterpreterType* pit, /*out*/UINT* pFldSize, /*out*/bool* pManagedMem); // We give out the address of this as the address for an "intrinsic static Zero". static INT64 IntrinsicStaticZero; // The version above does caching; this version always does the work. Returns "true" iff the results // are cacheable. bool StaticFldAddrWork(CORINFO_ACCESS_FLAGS accessFlgs, /*out (byref)*/void** pStaticFieldAddr, /*out*/InterpreterType* pit, /*out*/UINT* pFldSize, /*out*/bool* pManagedMem); // Ensure that pMT has been initialized (including running it's .cctor). static void EnsureClassInit(MethodTable* pMT); // Load/store array elements, get length. "T" should be the element // type of the array (as indicated by a LDELEM opcode with a type); "IsObjType" should // be true iff T is an object type, and "cit" should be the stack-normal CorInfoType // to push on the type stack. template<typename T, bool IsObjType, CorInfoType cit> void LdElemWithType(); // Load the address of an array element. template<typename T, bool IsObjType> void StElemWithType(); template<bool takeAddr> void LdElem(); void StElem(); void InitBlk(); void CpBlk(); void Box(); void UnboxAny(); void Unbox(); // Requires that operand stack location "i" contain a byref to a value of the struct type // "valCls". Boxes the referent of that byref, and substitutes the resulting object pointer // at opstack location "i." void BoxStructRefAt(unsigned ind, CORINFO_CLASS_HANDLE valCls); void Throw(); void Rethrow(); void EndFilter(); void LdLen(); // Perform a normal (non-constructor) call. The "virtualCall" argument indicates whether the // call should be virtual. void DoCall(bool virtualCall); // Perform a call. For normal (non-constructor) calls, all optional args should be // NULL (the default). For constructors, "thisArg" should be a this pointer (that is not on the operand stack), // and "callInfoPtr" should be the callInfo describing the constructor. There's a special case here: for "VAROBJSIZE" constructors // (which currently are defined for String), we want to explicitly pass NULL to the (pseudo) constructor. So passing // the special value "0x1" as "thisArg" will cause NULL to be pushed. void DoCallWork(bool virtualCall, void* thisArg = NULL, CORINFO_RESOLVED_TOKEN* methTokPtr = NULL, CORINFO_CALL_INFO* callInfoPtr = NULL); // Do the call-indirect operation. void CallI(); // Analyze the given method to see if it is a "dead simple" property getter: // * if instance, ldarg.0, ldfld, ret. // * if static, ldstfld ret. // More complicated forms in DBG. Sets *offsetOfLd" to the offset of the ldfld or ldstfld instruction. static bool IsDeadSimpleGetter(CEEInfo* info, MethodDesc* pMD, size_t* offsetOfLd); static const unsigned ILOffsetOfLdFldInDeadSimpleInstanceGetterDbg = 2; static const unsigned ILOffsetOfLdFldInDeadSimpleInstanceGetterOpt = 1; static const unsigned ILOffsetOfLdSFldInDeadSimpleStaticGetter = 0; // Here we handle a few intrinsic calls directly. void DoStringLength(); void DoStringGetChar(); void DoGetTypeFromHandle(); void DoByReferenceCtor(); void DoByReferenceValue(); void DoSIMDHwAccelerated(); void DoGetIsSupported(); // Returns the proper generics context for use in resolving tokens ("precise" in the sense of including generic instantiation // information). CORINFO_CONTEXT_HANDLE m_preciseGenericsContext; CORINFO_CONTEXT_HANDLE GetPreciseGenericsContext() { if (m_preciseGenericsContext == NULL) { m_preciseGenericsContext = m_methInfo->GetPreciseGenericsContext(m_thisArg, m_genericsCtxtArg); } return m_preciseGenericsContext; } // Process the "CONSTRAINED" prefix, recording the constraint on the "this" parameter. void RecordConstrainedCall(); // Emit a barrier if the m_volatile flag is set, and reset the flag. void BarrierIfVolatile() { if (m_volatileFlag) { MemoryBarrier(); m_volatileFlag = false; } } enum BinaryArithOpEnum { BA_Add, BA_Sub, BA_Mul, BA_Div, BA_Rem }; template<int op> __forceinline void BinaryArithOp(); // "IsIntType" must be true iff "T" is an integral type, and "cit" must correspond to // "T". "TypeIsUnchanged" implies that the proper type is already on the operand type stack. template<int op, typename T, bool IsIntType, CorInfoType cit, bool TypeIsUnchanged> __forceinline void BinaryArithOpWork(T val1, T val2); // "op" is a BinaryArithOpEnum above; actually, must be one "BA_Add", "BA_Sub", "BA_Mul". template<int op, bool asUnsigned> void BinaryArithOvfOp(); template<int op, typename T, CorInfoType cit, bool TypeIsUnchanged> void BinaryArithOvfOpWork(T val1, T val2); INT32 RemFunc(INT32 v1, INT32 v2) { return v1 % v2; } INT64 RemFunc(INT64 v1, INT64 v2) { return v1 % v2; } float RemFunc(float v1, float v2); double RemFunc(double v1, double v2); enum BinaryIntOpEnum { BIO_And, BIO_DivUn, BIO_Or, BIO_RemUn, BIO_Xor }; template<int op> void BinaryIntOp(); template<int op, typename T, CorInfoType cit, bool TypeIsUnchanged> void BinaryIntOpWork(T val1, T val2); template<int op> void ShiftOp(); template<int op, typename T, typename UT> void ShiftOpWork(unsigned op1idx, CorInfoType cit2); void Neg(); void Not(); // "T" should be the type indicated by the opcode. // "TIsUnsigned" should be true if "T" is an unsigned type. // "TCanHoldPtr" should be true if the type can hold a pointer (true for NativeInt and Long). // "TIsShort" should be true if "T" is less wide than Int32. // "cit" should be the *stack-normal* type of the converted value; even if "TIsShort", "cit" should be CORINFO_TYPE_INT. template<typename T, bool TIsUnsigned, bool TCanHoldPtr, bool TIsShort, CorInfoType cit> void Conv(); void ConvRUn(); // This version is for conversion to integral types. template<typename T, INT64 TMin, UINT64 TMax, bool TCanHoldPtr, CorInfoType cit> void ConvOvf(); // This version is for conversion to integral types. template<typename T, INT64 TMin, UINT64 TMax, bool TCanHoldPtr, CorInfoType cit> void ConvOvfUn(); void LdObj(); void LdObjValueClassWork(CORINFO_CLASS_HANDLE valueClsHnd, unsigned ind, void* src); void CpObj(); void StObj(); void InitObj(); void LdStr(); void NewObj(); void NewArr(); void IsInst(); void CastClass(); void MkRefany(); void RefanyType(); void RefanyVal(); void CkFinite(); void LdToken(); void LdFtn(); void LdVirtFtn(); // The JIT/EE machinery for transforming delegate constructor calls requires the // CORINFO_METHOD_HANDLE of a method. Usually, the method will be provided by a previous LDFTN/LDVIRTFTN. // In the JIT, we fold that previous instruction and the delegate constructor into a single tree, before morphing. // At this time, the loaded function is still in the form of a CORINFO_METHOD_HANDLE. At morph time, delegate constructor is transformed, // looking into the argument trees to find this handle. LDFTN's that are not removed this way are morphed to have actual native code addresses. // To support both of these needs, LDFTN will push the native code address of a method, as uses that actually need the value to invoke or store in // data structures require, but it will also ensure that this parallel stack is allocated, and set the corresponding index to hold the method handle. // When we call a delegate constructor, we find the method handle on this stack. CORINFO_METHOD_HANDLE* m_functionPointerStack; CORINFO_METHOD_HANDLE* GetFunctionPointerStack() { if (m_functionPointerStack == NULL) { m_functionPointerStack = new CORINFO_METHOD_HANDLE[m_methInfo->m_maxStack]; for (unsigned i = 0; i < m_methInfo->m_maxStack; i++) { m_functionPointerStack[i] = NULL; } } return m_functionPointerStack; } void Sizeof(); void LocAlloc(); #if INTERP_ILINSTR_PROFILE static void SetILInstrCategories(); // This type is used in sorting il instructions in a profile. struct InstrExecRecord { unsigned short m_instr; bool m_is2byte; unsigned m_execs; #if INTERP_ILCYCLE_PROFILE unsigned __int64 m_cycles; #endif // INTERP_ILCYCLE_PROFILE static int _cdecl Compare(const void* v0, const void* v1) { InstrExecRecord* iep0 = (InstrExecRecord*)v0; InstrExecRecord* iep1 = (InstrExecRecord*)v1; #if INTERP_ILCYCLE_PROFILE if (iep0->m_cycles > iep1->m_cycles) return -1; else if (iep0->m_cycles == iep1->m_cycles) return 0; else return 1; #else if (iep0->m_execs > iep1->m_execs) return -1; else if (iep0->m_execs == iep1->m_execs) return 0; else return 1; #endif // INTERP_ILCYCLE_PROFILE } }; // Prints the given array "recs", assumed to already be sorted. static void PrintILProfile(InstrExecRecord* recs, unsigned totInstrs #if INTERP_ILCYCLE_PROFILE , unsigned __int64 totCycles #endif // INTERP_ILCYCLE_PROFILE ); #endif // INTERP_ILINSTR_PROFILE static size_t GetTypedRefSize(CEEInfo* info); static CORINFO_CLASS_HANDLE GetTypedRefClsHnd(CEEInfo* info); static InterpreterType GetTypedRefIT(CEEInfo* info); OBJECTREF TypeHandleToTypeRef(TypeHandle* pth); CorInfoType GetTypeForPrimitiveValueClass(CORINFO_CLASS_HANDLE clsHnd); static bool s_initialized; static bool s_compilerStaticsInitialized; // This is the class handle for the struct type TypedRef (aka "Refany"). static CORINFO_CLASS_HANDLE s_TypedRefClsHnd; // This is the InterpreterType for the struct type TypedRef (aka "Refany"). static InterpreterType s_TypedRefIT; // And this is the size of that struct. static size_t s_TypedRefSize; // This returns the class corresponding to the token, of kind "tokKind", at "codePtr". If this // includes any runtime lookup via a generics context parameter, does that. CORINFO_CLASS_HANDLE GetTypeFromToken(BYTE* codePtr, CorInfoTokenKind tokKind InterpTracingArg(ResolveTokenKind rtk)); // Calls m_interpCeeInfo.resolveToken inline void ResolveToken(CORINFO_RESOLVED_TOKEN* resTok, mdToken token, CorInfoTokenKind tokenType InterpTracingArg(ResolveTokenKind rtk)); inline FieldDesc* FindField(unsigned metaTok InterpTracingArg(ResolveTokenKind rtk)); inline CORINFO_CLASS_HANDLE FindClass(unsigned metaTok InterpTracingArg(ResolveTokenKind rtk)); enum CompareOpEnum { CO_EQ, CO_GT, CO_GT_UN, CO_LT, CO_LT_UN }; // It does not help making these next two inline functions (taking the // template arg as a "real" arg). template<int compOp> void CompareOp(); // Requires that the m_curStackHt is at least op1Idx+2. // Returns the result (0 or 1) of the comparison "opStack[op1Idx] op opStack[op1Idx + 1]". template<int compOp> INT32 CompareOpRes(unsigned op1Idx); // Making this inline, by making its arguments real arguments, // and using __forceinline didn't result in material difference. template<bool val, int targetLen> void BrOnValue(); // A worker function for BrOnValue. Assumes that "shouldBranch" indicates whether // a branch should be taken, and that "targetLen" is the length of the branch offset (1 or 4). // Updates "m_ILCodePtr" to the branch target if "shouldBranch" is true, or else // he next instruction (+ 1 + targetLength). __forceinline void BrOnValueTakeBranch(bool shouldBranch, int targetLen); template<int compOp, bool reverse, int targetLen> void BrOnComparison(); inline static INT8 getI1(const BYTE * ptr) { return *(INT8*)ptr; } inline static UINT16 getU2LittleEndian(const BYTE * ptr) { return VAL16(*(UNALIGNED UINT16*)ptr); } inline static UINT32 getU4LittleEndian(const BYTE * ptr) { return VAL32(*(UNALIGNED UINT32*)ptr); } inline static INT32 getI4LittleEndian(const BYTE * ptr) { return VAL32(*(UNALIGNED INT32*)ptr); } inline static INT64 getI8LittleEndian(const BYTE * ptr) { return VAL64(*(UNALIGNED INT64*)ptr); } void VerificationError(const char* msg); void ThrowDivideByZero(); void ThrowSysArithException(); void ThrowNullPointerException(); void ThrowOverflowException(); void ThrowArrayBoundsException(); void ThrowInvalidCastException(); void ThrowStackOverflow(); void ThrowOnInvalidPointer(void* ptr); #ifdef _DEBUG bool TOSIsPtr(); #endif #if INTERP_TRACING // Code copied from eeinterface.cpp in "compiler". Should be common... const char* eeGetMethodFullName(CORINFO_METHOD_HANDLE hnd); #endif // INTERP_TRACING }; #if defined(HOST_X86) inline unsigned short Interpreter::NumberOfIntegerRegArgs() { return 2; } #elif defined(HOST_AMD64) unsigned short Interpreter::NumberOfIntegerRegArgs() { #if defined(UNIX_AMD64_ABI) return 6; #else return 4; #endif } #elif defined(HOST_ARM) unsigned short Interpreter::NumberOfIntegerRegArgs() { return 4; } #elif defined(HOST_ARM64) unsigned short Interpreter::NumberOfIntegerRegArgs() { return 8; } #else #error Unsupported architecture. #endif #endif // INTERPRETER_H_DEFINED
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/jit/smcommon.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // Common headers used both in smgen.exe and the JIT. // #ifndef __sm_common_h__ #define __sm_common_h__ #include "smopenum.h" #define NUM_SM_STATES 250 typedef BYTE SM_STATE_ID; static_assert_no_msg(sizeof(SM_STATE_ID) == 1); // To conserve memory, we don't want to have more than 256 states. #define SM_STATE_ID_START 1 static_assert_no_msg(SM_STATE_ID_START == 1); // Make sure nobody changes it. We rely on this to map the SM_OPCODE // to single-opcode states. For example, in GetWeightForOpcode(). struct JumpTableCell { SM_STATE_ID srcState; SM_STATE_ID destState; }; struct SMState { bool term; // does this state terminate a code sequence? BYTE length; // the length of currently matched opcodes SM_STATE_ID longestTermState; // the ID of the longest matched terminate state SM_STATE_ID prevState; // previous state SM_OPCODE opc; // opcode that leads from the previous state to current state unsigned short jumpTableByteOffset; }; // // Code sequences // #define MAX_CODE_SEQUENCE_LENGTH 7 #define CODE_SEQUENCE_END ((SM_OPCODE)(SM_COUNT + 1)) #endif /* __sm_common_h__ */
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // Common headers used both in smgen.exe and the JIT. // #ifndef __sm_common_h__ #define __sm_common_h__ #include "smopenum.h" #define NUM_SM_STATES 250 typedef BYTE SM_STATE_ID; static_assert_no_msg(sizeof(SM_STATE_ID) == 1); // To conserve memory, we don't want to have more than 256 states. #define SM_STATE_ID_START 1 static_assert_no_msg(SM_STATE_ID_START == 1); // Make sure nobody changes it. We rely on this to map the SM_OPCODE // to single-opcode states. For example, in GetWeightForOpcode(). struct JumpTableCell { SM_STATE_ID srcState; SM_STATE_ID destState; }; struct SMState { bool term; // does this state terminate a code sequence? BYTE length; // the length of currently matched opcodes SM_STATE_ID longestTermState; // the ID of the longest matched terminate state SM_STATE_ID prevState; // previous state SM_OPCODE opc; // opcode that leads from the previous state to current state unsigned short jumpTableByteOffset; }; // // Code sequences // #define MAX_CODE_SEQUENCE_LENGTH 7 #define CODE_SEQUENCE_END ((SM_OPCODE)(SM_COUNT + 1)) #endif /* __sm_common_h__ */
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/mono/mono/component/debugger-engine.h
/** * \file */ #ifndef __MONO_DEBUGGER_ENGINE_COMPONENT_H__ #define __MONO_DEBUGGER_ENGINE_COMPONENT_H__ #include <mono/mini/mini.h> #include <mono/metadata/seq-points-data.h> #include "debugger-state-machine.h" #include <mono/metadata/mono-debug.h> #include <mono/mini/interp/interp-internals.h> #include "debugger-protocol.h" #define ModifierKind MdbgProtModifierKind #define StepDepth MdbgProtStepDepth #define StepSize MdbgProtStepSize #define StepFilter MdbgProtStepFilter #define EventKind MdbgProtEventKind #define CommandSet MdbgProtCommandSet #define EVENT_KIND_BREAKPOINT MDBGPROT_EVENT_KIND_BREAKPOINT #define EVENT_KIND_STEP MDBGPROT_EVENT_KIND_STEP #define EVENT_KIND_KEEPALIVE MDBGPROT_EVENT_KIND_KEEPALIVE #define EVENT_KIND_METHOD_ENTRY MDBGPROT_EVENT_KIND_METHOD_ENTRY #define EVENT_KIND_METHOD_EXIT MDBGPROT_EVENT_KIND_METHOD_EXIT #define EVENT_KIND_APPDOMAIN_CREATE MDBGPROT_EVENT_KIND_APPDOMAIN_CREATE #define EVENT_KIND_APPDOMAIN_UNLOAD MDBGPROT_EVENT_KIND_APPDOMAIN_UNLOAD #define EVENT_KIND_THREAD_START MDBGPROT_EVENT_KIND_THREAD_START #define EVENT_KIND_THREAD_DEATH MDBGPROT_EVENT_KIND_THREAD_DEATH #define EVENT_KIND_ASSEMBLY_LOAD MDBGPROT_EVENT_KIND_ASSEMBLY_LOAD #define EVENT_KIND_ASSEMBLY_UNLOAD MDBGPROT_EVENT_KIND_ASSEMBLY_UNLOAD #define EVENT_KIND_TYPE_LOAD MDBGPROT_EVENT_KIND_TYPE_LOAD #define EVENT_KIND_VM_START MDBGPROT_EVENT_KIND_VM_START #define EVENT_KIND_VM_DEATH MDBGPROT_EVENT_KIND_VM_DEATH #define EVENT_KIND_CRASH MDBGPROT_EVENT_KIND_CRASH #define EVENT_KIND_EXCEPTION MDBGPROT_EVENT_KIND_EXCEPTION #define EVENT_KIND_USER_BREAK MDBGPROT_EVENT_KIND_USER_BREAK #define EVENT_KIND_USER_LOG MDBGPROT_EVENT_KIND_USER_LOG #define CMD_EVENT_REQUEST_SET MDBGPROT_CMD_EVENT_REQUEST_SET #define CMD_EVENT_REQUEST_CLEAR MDBGPROT_CMD_EVENT_REQUEST_CLEAR #define CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS MDBGPROT_CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS #define CMD_VM_VERSION MDBGPROT_CMD_VM_VERSION #define CMD_VM_SET_PROTOCOL_VERSION MDBGPROT_CMD_VM_SET_PROTOCOL_VERSION #define CMD_VM_ALL_THREADS MDBGPROT_CMD_VM_ALL_THREADS #define CMD_VM_SUSPEND MDBGPROT_CMD_VM_SUSPEND #define CMD_VM_RESUME MDBGPROT_CMD_VM_RESUME #define CMD_VM_DISPOSE MDBGPROT_CMD_VM_DISPOSE #define CMD_VM_EXIT MDBGPROT_CMD_VM_EXIT #define CMD_VM_INVOKE_METHOD MDBGPROT_CMD_VM_INVOKE_METHOD #define CMD_VM_INVOKE_METHODS MDBGPROT_CMD_VM_INVOKE_METHODS #define CMD_VM_ABORT_INVOKE MDBGPROT_CMD_VM_ABORT_INVOKE #define CMD_VM_SET_KEEPALIVE MDBGPROT_CMD_VM_SET_KEEPALIVE #define CMD_VM_GET_TYPES_FOR_SOURCE_FILE MDBGPROT_CMD_VM_GET_TYPES_FOR_SOURCE_FILE #define CMD_VM_GET_TYPES MDBGPROT_CMD_VM_GET_TYPES #define CMD_VM_START_BUFFERING MDBGPROT_CMD_VM_START_BUFFERING #define CMD_VM_STOP_BUFFERING MDBGPROT_CMD_VM_STOP_BUFFERING #define CMD_APPDOMAIN_GET_ROOT_DOMAIN MDBGPROT_CMD_APPDOMAIN_GET_ROOT_DOMAIN #define CMD_APPDOMAIN_GET_FRIENDLY_NAME MDBGPROT_CMD_APPDOMAIN_GET_FRIENDLY_NAME #define CMD_APPDOMAIN_GET_ASSEMBLIES MDBGPROT_CMD_APPDOMAIN_GET_ASSEMBLIES #define CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY MDBGPROT_CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY #define CMD_APPDOMAIN_GET_CORLIB MDBGPROT_CMD_APPDOMAIN_GET_CORLIB #define CMD_APPDOMAIN_CREATE_STRING MDBGPROT_CMD_APPDOMAIN_CREATE_STRING #define CMD_APPDOMAIN_CREATE_BYTE_ARRAY MDBGPROT_CMD_APPDOMAIN_CREATE_BYTE_ARRAY #define CMD_APPDOMAIN_CREATE_BOXED_VALUE MDBGPROT_CMD_APPDOMAIN_CREATE_BOXED_VALUE #define CMD_ASSEMBLY_GET_LOCATION MDBGPROT_CMD_ASSEMBLY_GET_LOCATION #define CMD_ASSEMBLY_GET_ENTRY_POINT MDBGPROT_CMD_ASSEMBLY_GET_ENTRY_POINT #define CMD_ASSEMBLY_GET_MANIFEST_MODULE MDBGPROT_CMD_ASSEMBLY_GET_MANIFEST_MODULE #define CMD_ASSEMBLY_GET_OBJECT MDBGPROT_CMD_ASSEMBLY_GET_OBJECT #define CMD_ASSEMBLY_GET_DOMAIN MDBGPROT_CMD_ASSEMBLY_GET_DOMAIN #define CMD_ASSEMBLY_GET_TYPE MDBGPROT_CMD_ASSEMBLY_GET_TYPE #define CMD_ASSEMBLY_GET_NAME MDBGPROT_CMD_ASSEMBLY_GET_NAME #define CMD_ASSEMBLY_GET_METADATA_BLOB MDBGPROT_CMD_ASSEMBLY_GET_METADATA_BLOB #define CMD_ASSEMBLY_GET_IS_DYNAMIC MDBGPROT_CMD_ASSEMBLY_GET_IS_DYNAMIC #define CMD_ASSEMBLY_GET_PDB_BLOB MDBGPROT_CMD_ASSEMBLY_GET_PDB_BLOB #define CMD_ASSEMBLY_GET_TYPE_FROM_TOKEN MDBGPROT_CMD_ASSEMBLY_GET_TYPE_FROM_TOKEN #define CMD_ASSEMBLY_GET_METHOD_FROM_TOKEN MDBGPROT_CMD_ASSEMBLY_GET_METHOD_FROM_TOKEN #define CMD_ASSEMBLY_HAS_DEBUG_INFO MDBGPROT_CMD_ASSEMBLY_HAS_DEBUG_INFO #define CMD_ASSEMBLY_GET_CATTRS MDBGPROT_CMD_ASSEMBLY_GET_CATTRS #define CMD_MODULE_GET_INFO MDBGPROT_CMD_MODULE_GET_INFO #define CMD_FIELD_GET_INFO MDBGPROT_CMD_FIELD_GET_INFO #define CMD_TYPE_GET_INFO MDBGPROT_CMD_TYPE_GET_INFO #define CMD_TYPE_GET_METHODS MDBGPROT_CMD_TYPE_GET_METHODS #define CMD_TYPE_GET_FIELDS MDBGPROT_CMD_TYPE_GET_FIELDS #define CMD_TYPE_GET_PROPERTIES MDBGPROT_CMD_TYPE_GET_PROPERTIES #define CMD_TYPE_GET_CATTRS MDBGPROT_CMD_TYPE_GET_CATTRS #define CMD_TYPE_GET_FIELD_CATTRS MDBGPROT_CMD_TYPE_GET_FIELD_CATTRS #define CMD_TYPE_GET_PROPERTY_CATTRS MDBGPROT_CMD_TYPE_GET_PROPERTY_CATTRS #define CMD_TYPE_GET_VALUES MDBGPROT_CMD_TYPE_GET_VALUES #define CMD_TYPE_GET_VALUES_2 MDBGPROT_CMD_TYPE_GET_VALUES_2 #define CMD_TYPE_SET_VALUES MDBGPROT_CMD_TYPE_SET_VALUES #define CMD_TYPE_GET_OBJECT MDBGPROT_CMD_TYPE_GET_OBJECT #define CMD_TYPE_GET_SOURCE_FILES MDBGPROT_CMD_TYPE_GET_SOURCE_FILES #define CMD_TYPE_GET_SOURCE_FILES_2 MDBGPROT_CMD_TYPE_GET_SOURCE_FILES_2 #define CMD_TYPE_IS_ASSIGNABLE_FROM MDBGPROT_CMD_TYPE_IS_ASSIGNABLE_FROM #define CMD_TYPE_GET_METHODS_BY_NAME_FLAGS MDBGPROT_CMD_TYPE_GET_METHODS_BY_NAME_FLAGS #define CMD_TYPE_GET_INTERFACES MDBGPROT_CMD_TYPE_GET_INTERFACES #define CMD_TYPE_GET_INTERFACE_MAP MDBGPROT_CMD_TYPE_GET_INTERFACE_MAP #define CMD_TYPE_IS_INITIALIZED MDBGPROT_CMD_TYPE_IS_INITIALIZED #define CMD_TYPE_CREATE_INSTANCE MDBGPROT_CMD_TYPE_CREATE_INSTANCE #define CMD_TYPE_GET_VALUE_SIZE MDBGPROT_CMD_TYPE_GET_VALUE_SIZE #define CMD_METHOD_GET_NAME MDBGPROT_CMD_METHOD_GET_NAME #define CMD_METHOD_GET_DECLARING_TYPE MDBGPROT_CMD_METHOD_GET_DECLARING_TYPE #define CMD_METHOD_GET_DEBUG_INFO MDBGPROT_CMD_METHOD_GET_DEBUG_INFO #define CMD_METHOD_GET_PARAM_INFO MDBGPROT_CMD_METHOD_GET_PARAM_INFO #define CMD_METHOD_GET_LOCALS_INFO MDBGPROT_CMD_METHOD_GET_LOCALS_INFO #define CMD_METHOD_GET_INFO MDBGPROT_CMD_METHOD_GET_INFO #define CMD_METHOD_GET_BODY MDBGPROT_CMD_METHOD_GET_BODY #define CMD_METHOD_RESOLVE_TOKEN MDBGPROT_CMD_METHOD_RESOLVE_TOKEN #define CMD_METHOD_GET_CATTRS MDBGPROT_CMD_METHOD_GET_CATTRS #define CMD_METHOD_MAKE_GENERIC_METHOD MDBGPROT_CMD_METHOD_MAKE_GENERIC_METHOD #define CMD_METHOD_TOKEN MDBGPROT_CMD_METHOD_TOKEN #define CMD_METHOD_ASSEMBLY MDBGPROT_CMD_METHOD_ASSEMBLY #define CMD_THREAD_GET_NAME MDBGPROT_CMD_THREAD_GET_NAME #define CMD_THREAD_GET_FRAME_INFO MDBGPROT_CMD_THREAD_GET_FRAME_INFO #define CMD_THREAD_GET_STATE MDBGPROT_CMD_THREAD_GET_STATE #define CMD_THREAD_GET_INFO MDBGPROT_CMD_THREAD_GET_INFO #define CMD_THREAD_GET_ID MDBGPROT_CMD_THREAD_GET_ID #define CMD_THREAD_GET_TID MDBGPROT_CMD_THREAD_GET_TID #define CMD_THREAD_SET_IP MDBGPROT_CMD_THREAD_SET_IP #define CMD_THREAD_ELAPSED_TIME MDBGPROT_CMD_THREAD_ELAPSED_TIME #define CMD_STACK_FRAME_GET_DOMAIN MDBGPROT_CMD_STACK_FRAME_GET_DOMAIN #define CMD_STACK_FRAME_GET_ARGUMENT MDBGPROT_CMD_STACK_FRAME_GET_ARGUMENT #define CMD_STACK_FRAME_GET_VALUES MDBGPROT_CMD_STACK_FRAME_GET_VALUES #define CMD_STACK_FRAME_GET_THIS MDBGPROT_CMD_STACK_FRAME_GET_THIS #define CMD_STACK_FRAME_SET_VALUES MDBGPROT_CMD_STACK_FRAME_SET_VALUES #define CMD_STACK_FRAME_GET_DOMAIN MDBGPROT_CMD_STACK_FRAME_GET_DOMAIN #define CMD_STACK_FRAME_SET_THIS MDBGPROT_CMD_STACK_FRAME_SET_THIS #define CMD_ARRAY_REF_GET_TYPE MDBGPROT_CMD_ARRAY_REF_GET_TYPE #define CMD_ARRAY_REF_GET_LENGTH MDBGPROT_CMD_ARRAY_REF_GET_LENGTH #define CMD_ARRAY_REF_GET_VALUES MDBGPROT_CMD_ARRAY_REF_GET_VALUES #define CMD_ARRAY_REF_SET_VALUES MDBGPROT_CMD_ARRAY_REF_SET_VALUES #define CMD_STRING_REF_GET_VALUE MDBGPROT_CMD_STRING_REF_GET_VALUE #define CMD_STRING_REF_GET_LENGTH MDBGPROT_CMD_STRING_REF_GET_LENGTH #define CMD_STRING_REF_GET_CHARS MDBGPROT_CMD_STRING_REF_GET_CHARS #define CMD_POINTER_GET_VALUE MDBGPROT_CMD_POINTER_GET_VALUE #define CMD_OBJECT_REF_IS_COLLECTED MDBGPROT_CMD_OBJECT_REF_IS_COLLECTED #define CMD_OBJECT_REF_GET_TYPE MDBGPROT_CMD_OBJECT_REF_GET_TYPE #define CMD_OBJECT_REF_GET_VALUES_ICORDBG MDBGPROT_CMD_OBJECT_REF_GET_VALUES_ICORDBG #define CMD_OBJECT_REF_GET_VALUES MDBGPROT_CMD_OBJECT_REF_GET_VALUES #define CMD_OBJECT_REF_SET_VALUES MDBGPROT_CMD_OBJECT_REF_SET_VALUES #define CMD_OBJECT_REF_GET_ADDRESS MDBGPROT_CMD_OBJECT_REF_GET_ADDRESS #define CMD_OBJECT_REF_GET_DOMAIN MDBGPROT_CMD_OBJECT_REF_GET_DOMAIN #define CMD_OBJECT_REF_GET_INFO MDBGPROT_CMD_OBJECT_REF_GET_INFO #define TOKEN_TYPE_METHOD MDBGPROT_TOKEN_TYPE_METHOD #define TOKEN_TYPE_UNKNOWN MDBGPROT_TOKEN_TYPE_UNKNOWN #define TOKEN_TYPE_FIELD MDBGPROT_TOKEN_TYPE_FIELD #define TOKEN_TYPE_METHOD MDBGPROT_TOKEN_TYPE_METHOD #define TOKEN_TYPE_STRING MDBGPROT_TOKEN_TYPE_STRING #define TOKEN_TYPE_TYPE MDBGPROT_TOKEN_TYPE_TYPE #define STEP_FILTER_STATIC_CTOR MDBGPROT_STEP_FILTER_STATIC_CTOR #define STEP_DEPTH_OVER MDBGPROT_STEP_DEPTH_OVER #define STEP_DEPTH_OUT MDBGPROT_STEP_DEPTH_OUT #define STEP_DEPTH_INTO MDBGPROT_STEP_DEPTH_INTO #define STEP_SIZE_MIN MDBGPROT_STEP_SIZE_MIN #define STEP_SIZE_LINE MDBGPROT_STEP_SIZE_LINE #define SUSPEND_POLICY_NONE MDBGPROT_SUSPEND_POLICY_NONE #define SUSPEND_POLICY_ALL MDBGPROT_SUSPEND_POLICY_ALL #define SUSPEND_POLICY_EVENT_THREAD MDBGPROT_SUSPEND_POLICY_EVENT_THREAD #define CMD_COMPOSITE MDBGPROT_CMD_COMPOSITE #define INVOKE_FLAG_SINGLE_THREADED MDBGPROT_INVOKE_FLAG_SINGLE_THREADED #define INVOKE_FLAG_VIRTUAL MDBGPROT_INVOKE_FLAG_VIRTUAL #define INVOKE_FLAG_DISABLE_BREAKPOINTS MDBGPROT_INVOKE_FLAG_DISABLE_BREAKPOINTS #define INVOKE_FLAG_RETURN_OUT_THIS MDBGPROT_INVOKE_FLAG_RETURN_OUT_THIS #define INVOKE_FLAG_RETURN_OUT_ARGS MDBGPROT_INVOKE_FLAG_RETURN_OUT_ARGS #define MOD_KIND_ASSEMBLY_ONLY MDBGPROT_MOD_KIND_ASSEMBLY_ONLY #define MOD_KIND_EXCEPTION_ONLY MDBGPROT_MOD_KIND_EXCEPTION_ONLY #define MOD_KIND_NONE MDBGPROT_MOD_KIND_NONE #define MOD_KIND_COUNT MDBGPROT_MOD_KIND_COUNT #define MOD_KIND_THREAD_ONLY MDBGPROT_MOD_KIND_THREAD_ONLY #define MOD_KIND_SOURCE_FILE_ONLY MDBGPROT_MOD_KIND_SOURCE_FILE_ONLY #define MOD_KIND_TYPE_NAME_ONLY MDBGPROT_MOD_KIND_TYPE_NAME_ONLY #define MOD_KIND_STEP MDBGPROT_MOD_KIND_STEP #define MOD_KIND_LOCATION_ONLY MDBGPROT_MOD_KIND_LOCATION_ONLY #define STEP_FILTER_DEBUGGER_HIDDEN MDBGPROT_STEP_FILTER_DEBUGGER_HIDDEN #define STEP_FILTER_DEBUGGER_NON_USER_CODE MDBGPROT_STEP_FILTER_DEBUGGER_NON_USER_CODE #define STEP_FILTER_DEBUGGER_STEP_THROUGH MDBGPROT_STEP_FILTER_DEBUGGER_STEP_THROUGH #define STEP_FILTER_NONE MDBGPROT_STEP_FILTER_NONE #define ERR_NONE MDBGPROT_ERR_NONE #define ERR_INVOKE_ABORTED MDBGPROT_ERR_INVOKE_ABORTED #define ERR_NOT_SUSPENDED MDBGPROT_ERR_NOT_SUSPENDED #define ERR_INVALID_ARGUMENT MDBGPROT_ERR_INVALID_ARGUMENT #define ERR_INVALID_OBJECT MDBGPROT_ERR_INVALID_OBJECT #define ERR_UNLOADED MDBGPROT_ERR_UNLOADED #define ERR_NOT_IMPLEMENTED MDBGPROT_ERR_NOT_IMPLEMENTED #define ERR_LOADER_ERROR MDBGPROT_ERR_LOADER_ERROR #define ERR_NO_INVOCATION MDBGPROT_ERR_NO_INVOCATION #define ERR_NO_SEQ_POINT_AT_IL_OFFSET MDBGPROT_ERR_NO_SEQ_POINT_AT_IL_OFFSET #define ERR_INVALID_FIELDID MDBGPROT_ERR_INVALID_FIELDID #define ERR_INVALID_FRAMEID MDBGPROT_ERR_INVALID_FRAMEID #define ERR_ABSENT_INFORMATION MDBGPROT_ERR_ABSENT_INFORMATION #define VALUE_TYPE_ID_FIXED_ARRAY MDBGPROT_VALUE_TYPE_ID_FIXED_ARRAY #define VALUE_TYPE_ID_NULL MDBGPROT_VALUE_TYPE_ID_NULL #define VALUE_TYPE_ID_PARENT_VTYPE MDBGPROT_VALUE_TYPE_ID_PARENT_VTYPE #define VALUE_TYPE_ID_TYPE MDBGPROT_VALUE_TYPE_ID_TYPE #define CMD_SET_VM MDBGPROT_CMD_SET_VM #define CMD_SET_OBJECT_REF MDBGPROT_CMD_SET_OBJECT_REF #define CMD_SET_STRING_REF MDBGPROT_CMD_SET_STRING_REF #define CMD_SET_THREAD MDBGPROT_CMD_SET_THREAD #define CMD_SET_ARRAY_REF MDBGPROT_CMD_SET_ARRAY_REF #define CMD_SET_EVENT_REQUEST MDBGPROT_CMD_SET_EVENT_REQUEST #define CMD_SET_STACK_FRAME MDBGPROT_CMD_SET_STACK_FRAME #define CMD_SET_APPDOMAIN MDBGPROT_CMD_SET_APPDOMAIN #define CMD_SET_ASSEMBLY MDBGPROT_CMD_SET_ASSEMBLY #define CMD_SET_METHOD MDBGPROT_CMD_SET_METHOD #define CMD_SET_TYPE MDBGPROT_CMD_SET_TYPE #define CMD_SET_MODULE MDBGPROT_CMD_SET_MODULE #define CMD_SET_FIELD MDBGPROT_CMD_SET_FIELD #define CMD_SET_POINTER MDBGPROT_CMD_SET_POINTER #define CMD_SET_EVENT MDBGPROT_CMD_SET_EVENT #define Buffer MdbgProtBuffer #define ReplyPacket MdbgProtReplyPacket #define buffer_init m_dbgprot_buffer_init #define buffer_free m_dbgprot_buffer_free #define buffer_add_int m_dbgprot_buffer_add_int #define buffer_add_long m_dbgprot_buffer_add_long #define buffer_add_string m_dbgprot_buffer_add_string #define buffer_add_id m_dbgprot_buffer_add_id #define buffer_add_byte m_dbgprot_buffer_add_byte #define buffer_len m_dbgprot_buffer_len #define buffer_add_buffer m_dbgprot_buffer_add_buffer #define buffer_add_data m_dbgprot_buffer_add_data #define buffer_add_utf16 m_dbgprot_buffer_add_utf16 #define buffer_add_byte_array m_dbgprot_buffer_add_byte_array #define buffer_add_short m_dbgprot_buffer_add_short #define decode_id m_dbgprot_decode_id #define decode_int m_dbgprot_decode_int #define decode_byte m_dbgprot_decode_byte #define decode_long m_dbgprot_decode_long #define decode_string m_dbgprot_decode_string #define event_to_string m_dbgprot_event_to_string #define ErrorCode MdbgProtErrorCode #define FRAME_FLAG_DEBUGGER_INVOKE MDBGPROT_FRAME_FLAG_DEBUGGER_INVOKE #define FRAME_FLAG_NATIVE_TRANSITION MDBGPROT_FRAME_FLAG_NATIVE_TRANSITION /* * Contains information about an inserted breakpoint. */ typedef struct { long il_offset, native_offset; guint8 *ip; MonoJitInfo *ji; MonoDomain *domain; } BreakpointInstance; /* * OBJECT IDS */ /* * Represents an object accessible by the debugger client. */ typedef struct { /* Unique id used in the wire protocol to refer to objects */ int id; /* * A weakref gc handle pointing to the object. The gc handle is used to * detect if the object was garbage collected. */ MonoGCHandle handle; } ObjRef; typedef struct { //Must be the first field to ensure pointer equivalence DbgEngineStackFrame de; int id; guint32 il_offset; /* * If method is gshared, this is the actual instance, otherwise this is equal to * method. */ MonoMethod *actual_method; /* * This is the method which is visible to debugger clients. Same as method, * except for native-to-managed wrappers. */ MonoMethod *api_method; MonoContext ctx; MonoDebugMethodJitInfo *jit; MonoInterpFrameHandle interp_frame; gpointer frame_addr; int flags; host_mgreg_t *reg_locations [MONO_MAX_IREGS]; /* * Whenever ctx is set. This is FALSE for the last frame of running threads, since * the frame can become invalid. */ gboolean has_ctx; } StackFrame; #define DE_ERR_NONE 0 // WARNING WARNING WARNING // Error codes MUST match those of sdb for now #define DE_ERR_NOT_IMPLEMENTED 100 MonoGHashTable * mono_debugger_get_thread_states (void); gboolean mono_debugger_is_disconnected (void); gsize mono_debugger_tls_thread_id (DebuggerTlsData *debuggerTlsData); void mono_debugger_set_thread_state (DebuggerTlsData *ref, MonoDebuggerThreadState expected, MonoDebuggerThreadState set); MonoDebuggerThreadState mono_debugger_get_thread_state (DebuggerTlsData *ref); void mono_de_cleanup (void); void mono_de_set_log_level (int level, FILE *file); //locking - we expose the lock object from the debugging engine to ensure we keep the same locking semantics of sdb. void mono_de_lock (void); void mono_de_unlock (void); // domain handling void mono_de_foreach_domain (GHFunc func, gpointer user_data); void mono_de_domain_add (MonoDomain *domain); //breakpoints void mono_de_clear_breakpoint (MonoBreakpoint *bp); MonoBreakpoint* mono_de_set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error); void mono_de_collect_breakpoints_by_sp (SeqPoint *sp, MonoJitInfo *ji, GPtrArray *ss_reqs, GPtrArray *bp_reqs); void mono_de_clear_breakpoints_for_domain (MonoDomain *domain); void mono_de_add_pending_breakpoints(MonoMethod* method, MonoJitInfo* ji); //single stepping void mono_de_start_single_stepping (void); void mono_de_stop_single_stepping (void); void mono_de_process_breakpoint (void *tls, gboolean from_signal); void mono_de_process_single_step (void *tls, gboolean from_signal); DbgEngineErrorCode mono_de_ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req); void mono_de_cancel_ss (SingleStepReq *req); void mono_de_cancel_all_ss (void); DbgEngineErrorCode mono_de_set_interp_var (MonoType *t, gpointer addr, guint8 *val_buf); gboolean set_set_notification_for_wait_completion_flag (DbgEngineStackFrame *frame); MonoClass * get_class_to_get_builder_field(DbgEngineStackFrame *frame); gpointer get_async_method_builder (DbgEngineStackFrame *frame); MonoMethod* get_notify_debugger_of_wait_completion_method (void); MonoMethod* get_object_id_for_debugger_method (MonoClass* async_builder_class); void mono_debugger_free_objref(gpointer value); #ifdef HOST_ANDROID #define PRINT_DEBUG_MSG(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { g_print (__VA_ARGS__); } } while (0) #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; } } while (0) #elif HOST_WASM void wasm_debugger_log(int level, const gchar *format, ...); #define PRINT_DEBUG_MSG(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { wasm_debugger_log (level, __VA_ARGS__); } } while (0) #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; } } while (0) #elif defined(HOST_WIN32) && !HAVE_API_SUPPORT_WIN32_CONSOLE void win32_debugger_log(FILE *stream, const gchar *format, ...); #define PRINT_DEBUG_MSG(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { win32_debugger_log (log_file, __VA_ARGS__); } } while (0) #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; } } while (0) #else #define PRINT_DEBUG_MSG(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { fprintf (log_file, __VA_ARGS__); fflush (log_file); } } while (0) #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0) #endif #endif #if defined(HOST_WIN32) && !HAVE_API_SUPPORT_WIN32_CONSOLE void win32_debugger_log(FILE *stream, const gchar *format, ...); #define PRINT_ERROR_MSG(...) win32_debugger_log (log_file, __VA_ARGS__) #define PRINT_MSG(...) win32_debugger_log (log_file, __VA_ARGS__) #else #define PRINT_ERROR_MSG(...) g_printerr (__VA_ARGS__) #define PRINT_MSG(...) g_print (__VA_ARGS__) #endif void mono_de_init(DebuggerEngineCallbacks* cbs);
/** * \file */ #ifndef __MONO_DEBUGGER_ENGINE_COMPONENT_H__ #define __MONO_DEBUGGER_ENGINE_COMPONENT_H__ #include <mono/mini/mini.h> #include <mono/metadata/seq-points-data.h> #include "debugger-state-machine.h" #include <mono/metadata/mono-debug.h> #include <mono/mini/interp/interp-internals.h> #include "debugger-protocol.h" #define ModifierKind MdbgProtModifierKind #define StepDepth MdbgProtStepDepth #define StepSize MdbgProtStepSize #define StepFilter MdbgProtStepFilter #define EventKind MdbgProtEventKind #define CommandSet MdbgProtCommandSet #define EVENT_KIND_BREAKPOINT MDBGPROT_EVENT_KIND_BREAKPOINT #define EVENT_KIND_STEP MDBGPROT_EVENT_KIND_STEP #define EVENT_KIND_KEEPALIVE MDBGPROT_EVENT_KIND_KEEPALIVE #define EVENT_KIND_METHOD_ENTRY MDBGPROT_EVENT_KIND_METHOD_ENTRY #define EVENT_KIND_METHOD_EXIT MDBGPROT_EVENT_KIND_METHOD_EXIT #define EVENT_KIND_APPDOMAIN_CREATE MDBGPROT_EVENT_KIND_APPDOMAIN_CREATE #define EVENT_KIND_APPDOMAIN_UNLOAD MDBGPROT_EVENT_KIND_APPDOMAIN_UNLOAD #define EVENT_KIND_THREAD_START MDBGPROT_EVENT_KIND_THREAD_START #define EVENT_KIND_THREAD_DEATH MDBGPROT_EVENT_KIND_THREAD_DEATH #define EVENT_KIND_ASSEMBLY_LOAD MDBGPROT_EVENT_KIND_ASSEMBLY_LOAD #define EVENT_KIND_ASSEMBLY_UNLOAD MDBGPROT_EVENT_KIND_ASSEMBLY_UNLOAD #define EVENT_KIND_TYPE_LOAD MDBGPROT_EVENT_KIND_TYPE_LOAD #define EVENT_KIND_VM_START MDBGPROT_EVENT_KIND_VM_START #define EVENT_KIND_VM_DEATH MDBGPROT_EVENT_KIND_VM_DEATH #define EVENT_KIND_CRASH MDBGPROT_EVENT_KIND_CRASH #define EVENT_KIND_EXCEPTION MDBGPROT_EVENT_KIND_EXCEPTION #define EVENT_KIND_USER_BREAK MDBGPROT_EVENT_KIND_USER_BREAK #define EVENT_KIND_USER_LOG MDBGPROT_EVENT_KIND_USER_LOG #define CMD_EVENT_REQUEST_SET MDBGPROT_CMD_EVENT_REQUEST_SET #define CMD_EVENT_REQUEST_CLEAR MDBGPROT_CMD_EVENT_REQUEST_CLEAR #define CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS MDBGPROT_CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS #define CMD_VM_VERSION MDBGPROT_CMD_VM_VERSION #define CMD_VM_SET_PROTOCOL_VERSION MDBGPROT_CMD_VM_SET_PROTOCOL_VERSION #define CMD_VM_ALL_THREADS MDBGPROT_CMD_VM_ALL_THREADS #define CMD_VM_SUSPEND MDBGPROT_CMD_VM_SUSPEND #define CMD_VM_RESUME MDBGPROT_CMD_VM_RESUME #define CMD_VM_DISPOSE MDBGPROT_CMD_VM_DISPOSE #define CMD_VM_EXIT MDBGPROT_CMD_VM_EXIT #define CMD_VM_INVOKE_METHOD MDBGPROT_CMD_VM_INVOKE_METHOD #define CMD_VM_INVOKE_METHODS MDBGPROT_CMD_VM_INVOKE_METHODS #define CMD_VM_ABORT_INVOKE MDBGPROT_CMD_VM_ABORT_INVOKE #define CMD_VM_SET_KEEPALIVE MDBGPROT_CMD_VM_SET_KEEPALIVE #define CMD_VM_GET_TYPES_FOR_SOURCE_FILE MDBGPROT_CMD_VM_GET_TYPES_FOR_SOURCE_FILE #define CMD_VM_GET_TYPES MDBGPROT_CMD_VM_GET_TYPES #define CMD_VM_START_BUFFERING MDBGPROT_CMD_VM_START_BUFFERING #define CMD_VM_STOP_BUFFERING MDBGPROT_CMD_VM_STOP_BUFFERING #define CMD_APPDOMAIN_GET_ROOT_DOMAIN MDBGPROT_CMD_APPDOMAIN_GET_ROOT_DOMAIN #define CMD_APPDOMAIN_GET_FRIENDLY_NAME MDBGPROT_CMD_APPDOMAIN_GET_FRIENDLY_NAME #define CMD_APPDOMAIN_GET_ASSEMBLIES MDBGPROT_CMD_APPDOMAIN_GET_ASSEMBLIES #define CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY MDBGPROT_CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY #define CMD_APPDOMAIN_GET_CORLIB MDBGPROT_CMD_APPDOMAIN_GET_CORLIB #define CMD_APPDOMAIN_CREATE_STRING MDBGPROT_CMD_APPDOMAIN_CREATE_STRING #define CMD_APPDOMAIN_CREATE_BYTE_ARRAY MDBGPROT_CMD_APPDOMAIN_CREATE_BYTE_ARRAY #define CMD_APPDOMAIN_CREATE_BOXED_VALUE MDBGPROT_CMD_APPDOMAIN_CREATE_BOXED_VALUE #define CMD_ASSEMBLY_GET_LOCATION MDBGPROT_CMD_ASSEMBLY_GET_LOCATION #define CMD_ASSEMBLY_GET_ENTRY_POINT MDBGPROT_CMD_ASSEMBLY_GET_ENTRY_POINT #define CMD_ASSEMBLY_GET_MANIFEST_MODULE MDBGPROT_CMD_ASSEMBLY_GET_MANIFEST_MODULE #define CMD_ASSEMBLY_GET_OBJECT MDBGPROT_CMD_ASSEMBLY_GET_OBJECT #define CMD_ASSEMBLY_GET_DOMAIN MDBGPROT_CMD_ASSEMBLY_GET_DOMAIN #define CMD_ASSEMBLY_GET_TYPE MDBGPROT_CMD_ASSEMBLY_GET_TYPE #define CMD_ASSEMBLY_GET_NAME MDBGPROT_CMD_ASSEMBLY_GET_NAME #define CMD_ASSEMBLY_GET_METADATA_BLOB MDBGPROT_CMD_ASSEMBLY_GET_METADATA_BLOB #define CMD_ASSEMBLY_GET_IS_DYNAMIC MDBGPROT_CMD_ASSEMBLY_GET_IS_DYNAMIC #define CMD_ASSEMBLY_GET_PDB_BLOB MDBGPROT_CMD_ASSEMBLY_GET_PDB_BLOB #define CMD_ASSEMBLY_GET_TYPE_FROM_TOKEN MDBGPROT_CMD_ASSEMBLY_GET_TYPE_FROM_TOKEN #define CMD_ASSEMBLY_GET_METHOD_FROM_TOKEN MDBGPROT_CMD_ASSEMBLY_GET_METHOD_FROM_TOKEN #define CMD_ASSEMBLY_HAS_DEBUG_INFO MDBGPROT_CMD_ASSEMBLY_HAS_DEBUG_INFO #define CMD_ASSEMBLY_GET_CATTRS MDBGPROT_CMD_ASSEMBLY_GET_CATTRS #define CMD_MODULE_GET_INFO MDBGPROT_CMD_MODULE_GET_INFO #define CMD_FIELD_GET_INFO MDBGPROT_CMD_FIELD_GET_INFO #define CMD_TYPE_GET_INFO MDBGPROT_CMD_TYPE_GET_INFO #define CMD_TYPE_GET_METHODS MDBGPROT_CMD_TYPE_GET_METHODS #define CMD_TYPE_GET_FIELDS MDBGPROT_CMD_TYPE_GET_FIELDS #define CMD_TYPE_GET_PROPERTIES MDBGPROT_CMD_TYPE_GET_PROPERTIES #define CMD_TYPE_GET_CATTRS MDBGPROT_CMD_TYPE_GET_CATTRS #define CMD_TYPE_GET_FIELD_CATTRS MDBGPROT_CMD_TYPE_GET_FIELD_CATTRS #define CMD_TYPE_GET_PROPERTY_CATTRS MDBGPROT_CMD_TYPE_GET_PROPERTY_CATTRS #define CMD_TYPE_GET_VALUES MDBGPROT_CMD_TYPE_GET_VALUES #define CMD_TYPE_GET_VALUES_2 MDBGPROT_CMD_TYPE_GET_VALUES_2 #define CMD_TYPE_SET_VALUES MDBGPROT_CMD_TYPE_SET_VALUES #define CMD_TYPE_GET_OBJECT MDBGPROT_CMD_TYPE_GET_OBJECT #define CMD_TYPE_GET_SOURCE_FILES MDBGPROT_CMD_TYPE_GET_SOURCE_FILES #define CMD_TYPE_GET_SOURCE_FILES_2 MDBGPROT_CMD_TYPE_GET_SOURCE_FILES_2 #define CMD_TYPE_IS_ASSIGNABLE_FROM MDBGPROT_CMD_TYPE_IS_ASSIGNABLE_FROM #define CMD_TYPE_GET_METHODS_BY_NAME_FLAGS MDBGPROT_CMD_TYPE_GET_METHODS_BY_NAME_FLAGS #define CMD_TYPE_GET_INTERFACES MDBGPROT_CMD_TYPE_GET_INTERFACES #define CMD_TYPE_GET_INTERFACE_MAP MDBGPROT_CMD_TYPE_GET_INTERFACE_MAP #define CMD_TYPE_IS_INITIALIZED MDBGPROT_CMD_TYPE_IS_INITIALIZED #define CMD_TYPE_CREATE_INSTANCE MDBGPROT_CMD_TYPE_CREATE_INSTANCE #define CMD_TYPE_GET_VALUE_SIZE MDBGPROT_CMD_TYPE_GET_VALUE_SIZE #define CMD_METHOD_GET_NAME MDBGPROT_CMD_METHOD_GET_NAME #define CMD_METHOD_GET_DECLARING_TYPE MDBGPROT_CMD_METHOD_GET_DECLARING_TYPE #define CMD_METHOD_GET_DEBUG_INFO MDBGPROT_CMD_METHOD_GET_DEBUG_INFO #define CMD_METHOD_GET_PARAM_INFO MDBGPROT_CMD_METHOD_GET_PARAM_INFO #define CMD_METHOD_GET_LOCALS_INFO MDBGPROT_CMD_METHOD_GET_LOCALS_INFO #define CMD_METHOD_GET_INFO MDBGPROT_CMD_METHOD_GET_INFO #define CMD_METHOD_GET_BODY MDBGPROT_CMD_METHOD_GET_BODY #define CMD_METHOD_RESOLVE_TOKEN MDBGPROT_CMD_METHOD_RESOLVE_TOKEN #define CMD_METHOD_GET_CATTRS MDBGPROT_CMD_METHOD_GET_CATTRS #define CMD_METHOD_MAKE_GENERIC_METHOD MDBGPROT_CMD_METHOD_MAKE_GENERIC_METHOD #define CMD_METHOD_TOKEN MDBGPROT_CMD_METHOD_TOKEN #define CMD_METHOD_ASSEMBLY MDBGPROT_CMD_METHOD_ASSEMBLY #define CMD_THREAD_GET_NAME MDBGPROT_CMD_THREAD_GET_NAME #define CMD_THREAD_GET_FRAME_INFO MDBGPROT_CMD_THREAD_GET_FRAME_INFO #define CMD_THREAD_GET_STATE MDBGPROT_CMD_THREAD_GET_STATE #define CMD_THREAD_GET_INFO MDBGPROT_CMD_THREAD_GET_INFO #define CMD_THREAD_GET_ID MDBGPROT_CMD_THREAD_GET_ID #define CMD_THREAD_GET_TID MDBGPROT_CMD_THREAD_GET_TID #define CMD_THREAD_SET_IP MDBGPROT_CMD_THREAD_SET_IP #define CMD_THREAD_ELAPSED_TIME MDBGPROT_CMD_THREAD_ELAPSED_TIME #define CMD_STACK_FRAME_GET_DOMAIN MDBGPROT_CMD_STACK_FRAME_GET_DOMAIN #define CMD_STACK_FRAME_GET_ARGUMENT MDBGPROT_CMD_STACK_FRAME_GET_ARGUMENT #define CMD_STACK_FRAME_GET_VALUES MDBGPROT_CMD_STACK_FRAME_GET_VALUES #define CMD_STACK_FRAME_GET_THIS MDBGPROT_CMD_STACK_FRAME_GET_THIS #define CMD_STACK_FRAME_SET_VALUES MDBGPROT_CMD_STACK_FRAME_SET_VALUES #define CMD_STACK_FRAME_GET_DOMAIN MDBGPROT_CMD_STACK_FRAME_GET_DOMAIN #define CMD_STACK_FRAME_SET_THIS MDBGPROT_CMD_STACK_FRAME_SET_THIS #define CMD_ARRAY_REF_GET_TYPE MDBGPROT_CMD_ARRAY_REF_GET_TYPE #define CMD_ARRAY_REF_GET_LENGTH MDBGPROT_CMD_ARRAY_REF_GET_LENGTH #define CMD_ARRAY_REF_GET_VALUES MDBGPROT_CMD_ARRAY_REF_GET_VALUES #define CMD_ARRAY_REF_SET_VALUES MDBGPROT_CMD_ARRAY_REF_SET_VALUES #define CMD_STRING_REF_GET_VALUE MDBGPROT_CMD_STRING_REF_GET_VALUE #define CMD_STRING_REF_GET_LENGTH MDBGPROT_CMD_STRING_REF_GET_LENGTH #define CMD_STRING_REF_GET_CHARS MDBGPROT_CMD_STRING_REF_GET_CHARS #define CMD_POINTER_GET_VALUE MDBGPROT_CMD_POINTER_GET_VALUE #define CMD_OBJECT_REF_IS_COLLECTED MDBGPROT_CMD_OBJECT_REF_IS_COLLECTED #define CMD_OBJECT_REF_GET_TYPE MDBGPROT_CMD_OBJECT_REF_GET_TYPE #define CMD_OBJECT_REF_GET_VALUES_ICORDBG MDBGPROT_CMD_OBJECT_REF_GET_VALUES_ICORDBG #define CMD_OBJECT_REF_GET_VALUES MDBGPROT_CMD_OBJECT_REF_GET_VALUES #define CMD_OBJECT_REF_SET_VALUES MDBGPROT_CMD_OBJECT_REF_SET_VALUES #define CMD_OBJECT_REF_GET_ADDRESS MDBGPROT_CMD_OBJECT_REF_GET_ADDRESS #define CMD_OBJECT_REF_GET_DOMAIN MDBGPROT_CMD_OBJECT_REF_GET_DOMAIN #define CMD_OBJECT_REF_GET_INFO MDBGPROT_CMD_OBJECT_REF_GET_INFO #define TOKEN_TYPE_METHOD MDBGPROT_TOKEN_TYPE_METHOD #define TOKEN_TYPE_UNKNOWN MDBGPROT_TOKEN_TYPE_UNKNOWN #define TOKEN_TYPE_FIELD MDBGPROT_TOKEN_TYPE_FIELD #define TOKEN_TYPE_METHOD MDBGPROT_TOKEN_TYPE_METHOD #define TOKEN_TYPE_STRING MDBGPROT_TOKEN_TYPE_STRING #define TOKEN_TYPE_TYPE MDBGPROT_TOKEN_TYPE_TYPE #define STEP_FILTER_STATIC_CTOR MDBGPROT_STEP_FILTER_STATIC_CTOR #define STEP_DEPTH_OVER MDBGPROT_STEP_DEPTH_OVER #define STEP_DEPTH_OUT MDBGPROT_STEP_DEPTH_OUT #define STEP_DEPTH_INTO MDBGPROT_STEP_DEPTH_INTO #define STEP_SIZE_MIN MDBGPROT_STEP_SIZE_MIN #define STEP_SIZE_LINE MDBGPROT_STEP_SIZE_LINE #define SUSPEND_POLICY_NONE MDBGPROT_SUSPEND_POLICY_NONE #define SUSPEND_POLICY_ALL MDBGPROT_SUSPEND_POLICY_ALL #define SUSPEND_POLICY_EVENT_THREAD MDBGPROT_SUSPEND_POLICY_EVENT_THREAD #define CMD_COMPOSITE MDBGPROT_CMD_COMPOSITE #define INVOKE_FLAG_SINGLE_THREADED MDBGPROT_INVOKE_FLAG_SINGLE_THREADED #define INVOKE_FLAG_VIRTUAL MDBGPROT_INVOKE_FLAG_VIRTUAL #define INVOKE_FLAG_DISABLE_BREAKPOINTS MDBGPROT_INVOKE_FLAG_DISABLE_BREAKPOINTS #define INVOKE_FLAG_RETURN_OUT_THIS MDBGPROT_INVOKE_FLAG_RETURN_OUT_THIS #define INVOKE_FLAG_RETURN_OUT_ARGS MDBGPROT_INVOKE_FLAG_RETURN_OUT_ARGS #define MOD_KIND_ASSEMBLY_ONLY MDBGPROT_MOD_KIND_ASSEMBLY_ONLY #define MOD_KIND_EXCEPTION_ONLY MDBGPROT_MOD_KIND_EXCEPTION_ONLY #define MOD_KIND_NONE MDBGPROT_MOD_KIND_NONE #define MOD_KIND_COUNT MDBGPROT_MOD_KIND_COUNT #define MOD_KIND_THREAD_ONLY MDBGPROT_MOD_KIND_THREAD_ONLY #define MOD_KIND_SOURCE_FILE_ONLY MDBGPROT_MOD_KIND_SOURCE_FILE_ONLY #define MOD_KIND_TYPE_NAME_ONLY MDBGPROT_MOD_KIND_TYPE_NAME_ONLY #define MOD_KIND_STEP MDBGPROT_MOD_KIND_STEP #define MOD_KIND_LOCATION_ONLY MDBGPROT_MOD_KIND_LOCATION_ONLY #define STEP_FILTER_DEBUGGER_HIDDEN MDBGPROT_STEP_FILTER_DEBUGGER_HIDDEN #define STEP_FILTER_DEBUGGER_NON_USER_CODE MDBGPROT_STEP_FILTER_DEBUGGER_NON_USER_CODE #define STEP_FILTER_DEBUGGER_STEP_THROUGH MDBGPROT_STEP_FILTER_DEBUGGER_STEP_THROUGH #define STEP_FILTER_NONE MDBGPROT_STEP_FILTER_NONE #define ERR_NONE MDBGPROT_ERR_NONE #define ERR_INVOKE_ABORTED MDBGPROT_ERR_INVOKE_ABORTED #define ERR_NOT_SUSPENDED MDBGPROT_ERR_NOT_SUSPENDED #define ERR_INVALID_ARGUMENT MDBGPROT_ERR_INVALID_ARGUMENT #define ERR_INVALID_OBJECT MDBGPROT_ERR_INVALID_OBJECT #define ERR_UNLOADED MDBGPROT_ERR_UNLOADED #define ERR_NOT_IMPLEMENTED MDBGPROT_ERR_NOT_IMPLEMENTED #define ERR_LOADER_ERROR MDBGPROT_ERR_LOADER_ERROR #define ERR_NO_INVOCATION MDBGPROT_ERR_NO_INVOCATION #define ERR_NO_SEQ_POINT_AT_IL_OFFSET MDBGPROT_ERR_NO_SEQ_POINT_AT_IL_OFFSET #define ERR_INVALID_FIELDID MDBGPROT_ERR_INVALID_FIELDID #define ERR_INVALID_FRAMEID MDBGPROT_ERR_INVALID_FRAMEID #define ERR_ABSENT_INFORMATION MDBGPROT_ERR_ABSENT_INFORMATION #define VALUE_TYPE_ID_FIXED_ARRAY MDBGPROT_VALUE_TYPE_ID_FIXED_ARRAY #define VALUE_TYPE_ID_NULL MDBGPROT_VALUE_TYPE_ID_NULL #define VALUE_TYPE_ID_PARENT_VTYPE MDBGPROT_VALUE_TYPE_ID_PARENT_VTYPE #define VALUE_TYPE_ID_TYPE MDBGPROT_VALUE_TYPE_ID_TYPE #define CMD_SET_VM MDBGPROT_CMD_SET_VM #define CMD_SET_OBJECT_REF MDBGPROT_CMD_SET_OBJECT_REF #define CMD_SET_STRING_REF MDBGPROT_CMD_SET_STRING_REF #define CMD_SET_THREAD MDBGPROT_CMD_SET_THREAD #define CMD_SET_ARRAY_REF MDBGPROT_CMD_SET_ARRAY_REF #define CMD_SET_EVENT_REQUEST MDBGPROT_CMD_SET_EVENT_REQUEST #define CMD_SET_STACK_FRAME MDBGPROT_CMD_SET_STACK_FRAME #define CMD_SET_APPDOMAIN MDBGPROT_CMD_SET_APPDOMAIN #define CMD_SET_ASSEMBLY MDBGPROT_CMD_SET_ASSEMBLY #define CMD_SET_METHOD MDBGPROT_CMD_SET_METHOD #define CMD_SET_TYPE MDBGPROT_CMD_SET_TYPE #define CMD_SET_MODULE MDBGPROT_CMD_SET_MODULE #define CMD_SET_FIELD MDBGPROT_CMD_SET_FIELD #define CMD_SET_POINTER MDBGPROT_CMD_SET_POINTER #define CMD_SET_EVENT MDBGPROT_CMD_SET_EVENT #define Buffer MdbgProtBuffer #define ReplyPacket MdbgProtReplyPacket #define buffer_init m_dbgprot_buffer_init #define buffer_free m_dbgprot_buffer_free #define buffer_add_int m_dbgprot_buffer_add_int #define buffer_add_long m_dbgprot_buffer_add_long #define buffer_add_string m_dbgprot_buffer_add_string #define buffer_add_id m_dbgprot_buffer_add_id #define buffer_add_byte m_dbgprot_buffer_add_byte #define buffer_len m_dbgprot_buffer_len #define buffer_add_buffer m_dbgprot_buffer_add_buffer #define buffer_add_data m_dbgprot_buffer_add_data #define buffer_add_utf16 m_dbgprot_buffer_add_utf16 #define buffer_add_byte_array m_dbgprot_buffer_add_byte_array #define buffer_add_short m_dbgprot_buffer_add_short #define decode_id m_dbgprot_decode_id #define decode_int m_dbgprot_decode_int #define decode_byte m_dbgprot_decode_byte #define decode_long m_dbgprot_decode_long #define decode_string m_dbgprot_decode_string #define event_to_string m_dbgprot_event_to_string #define ErrorCode MdbgProtErrorCode #define FRAME_FLAG_DEBUGGER_INVOKE MDBGPROT_FRAME_FLAG_DEBUGGER_INVOKE #define FRAME_FLAG_NATIVE_TRANSITION MDBGPROT_FRAME_FLAG_NATIVE_TRANSITION /* * Contains information about an inserted breakpoint. */ typedef struct { long il_offset, native_offset; guint8 *ip; MonoJitInfo *ji; MonoDomain *domain; } BreakpointInstance; /* * OBJECT IDS */ /* * Represents an object accessible by the debugger client. */ typedef struct { /* Unique id used in the wire protocol to refer to objects */ int id; /* * A weakref gc handle pointing to the object. The gc handle is used to * detect if the object was garbage collected. */ MonoGCHandle handle; } ObjRef; typedef struct { //Must be the first field to ensure pointer equivalence DbgEngineStackFrame de; int id; guint32 il_offset; /* * If method is gshared, this is the actual instance, otherwise this is equal to * method. */ MonoMethod *actual_method; /* * This is the method which is visible to debugger clients. Same as method, * except for native-to-managed wrappers. */ MonoMethod *api_method; MonoContext ctx; MonoDebugMethodJitInfo *jit; MonoInterpFrameHandle interp_frame; gpointer frame_addr; int flags; host_mgreg_t *reg_locations [MONO_MAX_IREGS]; /* * Whenever ctx is set. This is FALSE for the last frame of running threads, since * the frame can become invalid. */ gboolean has_ctx; } StackFrame; #define DE_ERR_NONE 0 // WARNING WARNING WARNING // Error codes MUST match those of sdb for now #define DE_ERR_NOT_IMPLEMENTED 100 MonoGHashTable * mono_debugger_get_thread_states (void); gboolean mono_debugger_is_disconnected (void); gsize mono_debugger_tls_thread_id (DebuggerTlsData *debuggerTlsData); void mono_debugger_set_thread_state (DebuggerTlsData *ref, MonoDebuggerThreadState expected, MonoDebuggerThreadState set); MonoDebuggerThreadState mono_debugger_get_thread_state (DebuggerTlsData *ref); void mono_de_cleanup (void); void mono_de_set_log_level (int level, FILE *file); //locking - we expose the lock object from the debugging engine to ensure we keep the same locking semantics of sdb. void mono_de_lock (void); void mono_de_unlock (void); // domain handling void mono_de_foreach_domain (GHFunc func, gpointer user_data); void mono_de_domain_add (MonoDomain *domain); //breakpoints void mono_de_clear_breakpoint (MonoBreakpoint *bp); MonoBreakpoint* mono_de_set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error); void mono_de_collect_breakpoints_by_sp (SeqPoint *sp, MonoJitInfo *ji, GPtrArray *ss_reqs, GPtrArray *bp_reqs); void mono_de_clear_breakpoints_for_domain (MonoDomain *domain); void mono_de_add_pending_breakpoints(MonoMethod* method, MonoJitInfo* ji); //single stepping void mono_de_start_single_stepping (void); void mono_de_stop_single_stepping (void); void mono_de_process_breakpoint (void *tls, gboolean from_signal); void mono_de_process_single_step (void *tls, gboolean from_signal); DbgEngineErrorCode mono_de_ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req); void mono_de_cancel_ss (SingleStepReq *req); void mono_de_cancel_all_ss (void); DbgEngineErrorCode mono_de_set_interp_var (MonoType *t, gpointer addr, guint8 *val_buf); gboolean set_set_notification_for_wait_completion_flag (DbgEngineStackFrame *frame); MonoClass * get_class_to_get_builder_field(DbgEngineStackFrame *frame); gpointer get_async_method_builder (DbgEngineStackFrame *frame); MonoMethod* get_notify_debugger_of_wait_completion_method (void); MonoMethod* get_object_id_for_debugger_method (MonoClass* async_builder_class); void mono_debugger_free_objref(gpointer value); #ifdef HOST_ANDROID #define PRINT_DEBUG_MSG(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { g_print (__VA_ARGS__); } } while (0) #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; } } while (0) #elif HOST_WASM void wasm_debugger_log(int level, const gchar *format, ...); #define PRINT_DEBUG_MSG(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { wasm_debugger_log (level, __VA_ARGS__); } } while (0) #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; } } while (0) #elif defined(HOST_WIN32) && !HAVE_API_SUPPORT_WIN32_CONSOLE void win32_debugger_log(FILE *stream, const gchar *format, ...); #define PRINT_DEBUG_MSG(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { win32_debugger_log (log_file, __VA_ARGS__); } } while (0) #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; } } while (0) #else #define PRINT_DEBUG_MSG(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { fprintf (log_file, __VA_ARGS__); fflush (log_file); } } while (0) #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0) #endif #endif #if defined(HOST_WIN32) && !HAVE_API_SUPPORT_WIN32_CONSOLE void win32_debugger_log(FILE *stream, const gchar *format, ...); #define PRINT_ERROR_MSG(...) win32_debugger_log (log_file, __VA_ARGS__) #define PRINT_MSG(...) win32_debugger_log (log_file, __VA_ARGS__) #else #define PRINT_ERROR_MSG(...) g_printerr (__VA_ARGS__) #define PRINT_MSG(...) g_print (__VA_ARGS__) #endif void mono_de_init(DebuggerEngineCallbacks* cbs);
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/nativeaot/Runtime/inc/daccess.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. //***************************************************************************** // File: daccess.h // // Support for external access of runtime data structures. These // macros and templates hide the details of pointer and data handling // so that data structures and code can be compiled to work both // in-process and through a special memory access layer. // // This code assumes the existence of two different pieces of code, // the target, the runtime code that is going to be examined, and // the host, the code that's doing the examining. Access to the // target is abstracted so the target may be a live process on the // same machine, a live process on a different machine, a dump file // or whatever. No assumptions should be made about accessibility // of the target. // // This code assumes that the data in the target is static. Any // time the target's data changes the interfaces must be reset so // that potentially stale data is discarded. // // This code is intended for read access and there is no // way to write data back currently. // // DAC-ized code: // - is read-only (non-invasive). So DACized codepaths can not trigger a GC. // - has no Thread* object. In reality, DAC-ized codepaths are // ReadProcessMemory calls from out-of-process. Conceptually, they // are like a pure-native (preemptive) thread. //// // This means that in particular, you cannot DACize a GCTRIGGERS function. // Neither can you DACize a function that throws if this will involve // allocating a new exception object. There may be // exceptions to these rules if you can guarantee that the DACized // part of the code path cannot cause a garbage collection (see // EditAndContinueModule::ResolveField for an example). // If you need to DACize a function that may trigger // a GC, it is probably best to refactor the function so that the DACized // part of the code path is in a separate function. For instance, // functions with GetOrCreate() semantics are hard to DAC-ize because // they the Create portion is inherently invasive. Instead, consider refactoring // into a GetOrFail() function that DAC can call; and then make GetOrCreate() // a wrapper around that. // // This code works by hiding the details of access to target memory. // Access is divided into two types: // 1. DPTR - access to a piece of data. // 2. VPTR - access to a class with a vtable. The class can only have // a single vtable pointer at the beginning of the class instance. // Things only need to be declared as VPTRs when it is necessary to // call virtual functions in the host. In that case the access layer // must do extra work to provide a host vtable for the object when // it is retrieved so that virtual functions can be called. // // When compiling with DACCESS_COMPILE the macros turn into templates // which replace pointers with smart pointers that know how to fetch // data from the target process and provide a host process version of it. // Normal data structure access will transparently receive a host copy // of the data and proceed, so code such as // typedef DPTR(Class) PTR_Class; // PTR_Class cls; // int val = cls->m_Int; // will work without modification. The appropriate operators are overloaded // to provide transparent access, such as the -> operator in this case. // Note that the convention is to create an appropriate typedef for // each type that will be accessed. This hides the particular details // of the type declaration and makes the usage look more like regular code. // // The ?PTR classes also have an implicit base type cast operator to // produce a host-pointer instance of the given type. For example // Class* cls = PTR_Class(addr); // works by implicit conversion from the PTR_Class created by wrapping // to a host-side Class instance. Again, this means that existing code // can work without modification. // // Code Example: // // typedef struct _rangesection // { // PTR_IJitManager pjit; // PTR_RangeSection pright; // PTR_RangeSection pleft; // ... Other fields omitted ... // } RangeSection; // // RangeSection* pRS = m_RangeTree; // // while (pRS != NULL) // { // if (currentPC < pRS->LowAddress) // pRS=pRS->pleft; // else if (currentPC > pRS->HighAddress) // pRS=pRS->pright; // else // { // return pRS->pjit; // } // } // // This code does not require any modifications. The global reference // provided by m_RangeTree will be a host version of the RangeSection // instantiated by conversion. The references to pRS->pleft and // pRS->pright will refer to DPTRs due to the modified declaration. // In the assignment statement the compiler will automatically use // the implicit conversion from PTR_RangeSection to RangeSection*, // causing a host instance to be created. Finally, if an appropriate // section is found the use of pRS->pjit will cause an implicit // conversion from PTR_IJitManager to IJitManager. The VPTR code // will look at target memory to determine the actual derived class // for the JitManager and instantiate the right class in the host so // that host virtual functions can be used just as they would in // the target. // // There are situations where code modifications are required, though. // // 1. Any time the actual value of an address matters, such as using // it as a search key in a tree, the target address must be used. // // An example of this is the RangeSection tree used to locate JIT // managers. A portion of this code is shown above. Each // RangeSection node in the tree describes a range of addresses // managed by the JitMan. These addresses are just being used as // values, not to dereference through, so there are not DPTRs. When // searching the range tree for an address the address used in the // search must be a target address as that's what values are kept in // the RangeSections. In the code shown above, currentPC must be a // target address as the RangeSections in the tree are all target // addresses. Use dac_cast<TADDR> to retrieve the target address // of a ?PTR, as well as to convert a host address to the // target address used to retrieve that particular instance. Do not // use dac_cast with any raw target pointer types (such as BYTE*). // // 2. Any time an address is modified, such as by address arithmetic, // the arithmetic must be performed on the target address. // // When a host instance is created it is created for the type in use. // There is no particular relation to any other instance, so address // arithmetic cannot be used to get from one instance to any other // part of memory. For example // char* Func(Class* cls) // { // // String follows the basic Class data. // return (char*)(cls + 1); // } // does not work with external access because the Class* used would // have retrieved only a Class worth of data. There is no string // following the host instance. Instead, this code should use // dac_cast<TADDR> to get the target address of the Class // instance, add sizeof(*cls) and then create a new ?PTR to access // the desired data. Note that the newly retrieved data will not // be contiguous with the Class instance, so address arithmetic // will still not work. // // Previous Code: // // BOOL IsTarget(LPVOID ip) // { // StubCallInstrs* pStubCallInstrs = GetStubCallInstrs(); // // if (ip == (LPVOID) &(pStubCallInstrs->m_op)) // { // return TRUE; // } // // Modified Code: // // BOOL IsTarget(LPVOID ip) // { // StubCallInstrs* pStubCallInstrs = GetStubCallInstrs(); // // if ((TADDR)ip == dac_cast<TADDR>(pStubCallInstrs) + // (TADDR)offsetof(StubCallInstrs, m_op)) // { // return TRUE; // } // // The parameter ip is a target address, so the host pStubCallInstrs // cannot be used to derive an address from. The member & reference // has to be replaced with a conversion from host to target address // followed by explicit offsetting for the field. // // PTR_HOST_MEMBER_TADDR is a convenience macro that encapsulates // these two operations, so the above code could also be: // // if ((TADDR)ip == // PTR_HOST_MEMBER_TADDR(StubCallInstrs, pStubCallInstrs, m_op)) // // 3. Any time the amount of memory referenced through an address // changes, such as by casting to a different type, a new ?PTR // must be created. // // Host instances are created and stored based on both the target // address and size of access. The access code has no way of knowing // all possible ways that data will be retrieved for a given address // so if code changes the way it accesses through an address a new // ?PTR must be used, which may lead to a difference instance and // different host address. This means that pointer identity does not hold // across casts, so code like // Class* cls = PTR_Class(addr); // Class2* cls2 = PTR_Class2(addr); // return cls == cls2; // will fail because the host-side instances have no relation to each // other. That isn't a problem, since by rule #1 you shouldn't be // relying on specific host address values. // // Previous Code: // // return (ArrayClass *) m_pMethTab->GetClass(); // // Modified Code: // // return PTR_ArrayClass(m_pMethTab->GetClass()); // // The ?PTR templates have an implicit conversion from a host pointer // to a target address, so the cast above constructs a new // PTR_ArrayClass by implicitly converting the host pointer result // from GetClass() to its target address and using that as the address // of the new PTR_ArrayClass. As mentioned, the actual host-side // pointer values may not be the same. // // Host pointer identity can be assumed as long as the type of access // is the same. In the example above, if both accesses were of type // Class then the host pointer will be the same, so it is safe to // retrieve the target address of an instance and then later get // a new host pointer for the target address using the same type as // the host pointer in that case will be the same. This is enabled // by caching all of the retrieved host instances. This cache is searched // by the addr:size pair and when there's a match the existing instance // is reused. This increases performance and also allows simple // pointer identity to hold. It does mean that host memory grows // in proportion to the amount of target memory being referenced, // so retrieving extraneous data should be avoided. // The host-side data cache grows until the Flush() method is called, // at which point all host-side data is discarded. No host // instance pointers should be held across a Flush(). // // Accessing into an object can lead to some unusual behavior. For // example, the SList class relies on objects to contain an SLink // instance that it uses for list maintenance. This SLink can be // embedded anywhere in the larger object. The SList access is always // purely to an SLink, so when using the access layer it will only // retrieve an SLink's worth of data. The SList template will then // do some address arithmetic to determine the start of the real // object and cast the resulting pointer to the final object type. // When using the access layer this results in a new ?PTR being // created and used, so a new instance will result. The internal // SLink instance will have no relation to the new object instance // even though in target address terms one is embedded in the other. // The assumption of data stability means that this won't cause // a problem, but care must be taken with the address arithmetic, // as layed out in rules #2 and #3. // // 4. Global address references cannot be used. Any reference to a // global piece of code or data, such as a function address, global // variable or class static variable, must be changed. // // The external access code may load at a different base address than // the target process code. Global addresses are therefore not // meaningful and must be replaced with something else. There isn't // a single solution, so replacements must be done on a case-by-case // basis. // // The simplest case is a global or class static variable. All // declarations must be replaced with a special declaration that // compiles into a modified accessor template value when compiled for // external data access. Uses of the variable automatically are fixed // up by the template instance. Note that assignment to the global // must be independently ifdef'ed as the external access layer should // not make any modifications. // // Macros allow for simple declaration of a class static and global // values that compile into an appropriate templated value. // // Previous Code: // // static RangeSection* m_RangeTree; // RangeSection* ExecutionManager::m_RangeTree; // // extern ThreadStore* g_pThreadStore; // ThreadStore* g_pThreadStore = &StaticStore; // class SystemDomain : public BaseDomain { // ... // ArrayListStatic m_appDomainIndexList; // ... // } // // SystemDomain::m_appDomainIndexList; // // extern DWORD gThreadTLSIndex; // // DWORD gThreadTLSIndex = TLS_OUT_OF_INDEXES; // // Modified Code: // // typedef DPTR(RangeSection) PTR_RangeSection; // SPTR_DECL(RangeSection, m_RangeTree); // SPTR_IMPL(RangeSection, ExecutionManager, m_RangeTree); // // typedef DPTR(ThreadStore) PTR_ThreadStore // GPTR_DECL(ThreadStore, g_pThreadStore); // GPTR_IMPL_INIT(ThreadStore, g_pThreadStore, &StaticStore); // // class SystemDomain : public BaseDomain { // ... // SVAL_DECL(ArrayListStatic; m_appDomainIndexList); // ... // } // // SVAL_IMPL(ArrayListStatic, SystemDomain, m_appDomainIndexList); // // GVAL_DECL(DWORD, gThreadTLSIndex); // // GVAL_IMPL_INIT(DWORD, gThreadTLSIndex, TLS_OUT_OF_INDEXES); // // When declaring the variable, the first argument declares the // variable's type and the second argument declares the variable's // name. When defining the variable the arguments are similar, with // an extra class name parameter for the static class variable case. // If an initializer is needed the IMPL_INIT macro should be used. // // Things get slightly more complicated when declaring an embedded // array. In this case the data element is not a single element and // therefore cannot be represented by a ?PTR. In the case of a global // array, you should use the GARY_DECL and GARY_IMPL macros. // We durrently have no support for declaring static array data members // or initialized arrays. Array data members that are dynamically allocated // need to be treated as pointer members. To reference individual elements // you must use pointer arithmetic (see rule 2 above). An array declared // as a local variable within a function does not need to be DACized. // // // All uses of ?VAL_DECL must have a corresponding entry given in the // DacGlobals structure in src\inc\dacvars.h. For SVAL_DECL the entry // is class__name. For GVAL_DECL the entry is dac__name. You must add // these entries in dacvars.h using the DEFINE_DACVAR macro. Note that // these entries also are used for dumping memory in mini dumps and // heap dumps. If it's not appropriate to dump a variable, (e.g., // it's an array or some other value that is not important to have // in a minidump) a second macro, DEFINE_DACVAR_NO_DUMP, will allow // you to make the required entry in the DacGlobals structure without // dumping its value. // // For convenience, here is a list of the various variable declaration and // initialization macros: // SVAL_DECL(type, name) static non-pointer data class MyClass // member declared within { // the class declaration // static int i; // SVAL_DECL(int, i); // } // // SVAL_IMPL(type, cls, name) static non-pointer data // int MyClass::i; // member defined outside SVAL_IMPL(int, MyClass, i); // the class declaration // // SVAL_IMPL_INIT(type, cls, static non-pointer data // int MyClass::i = 0; // name, val) member defined and SVAL_IMPL_INIT(int, MyClass, i, 0); // initialized outside the // class declaration // ------------------------------------------------------------------------------------------------ // SPTR_DECL(type, name) static pointer data class MyClass // member declared within { // the class declaration // static int * pInt; // SPTR_DECL(int, pInt); // } // // SPTR_IMPL(type, cls, name) static pointer data // int * MyClass::pInt; // member defined outside SPTR_IMPL(int, MyClass, pInt); // the class declaration // // SPTR_IMPL_INIT(type, cls, static pointer data // int * MyClass::pInt = NULL; // name, val) member defined and SPTR_IMPL_INIT(int, MyClass, pInt, NULL); // initialized outside the // class declaration // ------------------------------------------------------------------------------------------------ // GVAL_DECL(type, name) extern declaration of // extern int g_i // global non-pointer GVAL_DECL(int, g_i); // variable // // GVAL_IMPL(type, name) declaration of a // int g_i // global non-pointer GVAL_IMPL(int, g_i); // variable // // GVAL_IMPL_INIT (type, declaration and // int g_i = 0; // name, initialization of a GVAL_IMPL_INIT(int, g_i, 0); // val) global non-pointer // variable // ****Note**** // If you use GVAL_? to declare a global variable of a structured type and you need to // access a member of the type, you cannot use the dot operator. Instead, you must take the // address of the variable and use the arrow operator. For example: // struct // { // int x; // char ch; // } MyStruct; // GVAL_IMPL(MyStruct, g_myStruct); // int i = (&g_myStruct)->x; // ------------------------------------------------------------------------------------------------ // GPTR_DECL(type, name) extern declaration of // extern int * g_pInt // global pointer GPTR_DECL(int, g_pInt); // variable // // GPTR_IMPL(type, name) declaration of a // int * g_pInt // global pointer GPTR_IMPL(int, g_pInt); // variable // // GPTR_IMPL_INIT (type, declaration and // int * g_pInt = 0; // name, initialization of a GPTR_IMPL_INIT(int, g_pInt, NULL); // val) global pointer // variable // ------------------------------------------------------------------------------------------------ // GARY_DECL(type, name) extern declaration of // extern int g_rgIntList[MAX_ELEMENTS]; // a global array GPTR_DECL(int, g_rgIntList, MAX_ELEMENTS); // variable // // GARY_IMPL(type, name) declaration of a // int g_rgIntList[MAX_ELEMENTS]; // global pointer GPTR_IMPL(int, g_rgIntList, MAX_ELEMENTS); // variable // // // Certain pieces of code, such as the stack walker, rely on identifying // an object from its vtable address. As the target vtable addresses // do not necessarily correspond to the vtables used in the host, these // references must be translated. The access layer maintains translation // tables for all classes used with VPTR and can return the target // vtable pointer for any host vtable in the known list of VPTR classes. // // ----- Errors: // // All errors in the access layer are reported via exceptions. The // formal access layer methods catch all such exceptions and turn // them into the appropriate error, so this generally isn't visible // to users of the access layer. // // ----- DPTR Declaration: // // Create a typedef for the type with typedef DPTR(type) PTR_type; // Replace type* with PTR_type. // // ----- VPTR Declaration: // // VPTR can only be used on classes that have a single vtable // pointer at the beginning of the object. This should be true // for a normal single-inheritance object. // // All of the classes that may be instantiated need to be identified // and marked. In the base class declaration add either // VPTR_BASE_VTABLE_CLASS if the class is abstract or // VPTR_BASE_CONCRETE_VTABLE_CLASS if the class is concrete. In each // derived class add VPTR_VTABLE_CLASS. If you end up with compile or // link errors for an unresolved method called VPtrSize you missed a // derived class declaration. // // As described above, dac can only handle classes with a single // vtable. However, there's a special case for multiple inheritance // situations when only one of the classes is needed for dac. If // the base class needed is the first class in the derived class's // layout then it can be used with dac via using the VPTR_MULTI_CLASS // macros. Use with extreme care. // // All classes to be instantiated must be listed in src\inc\vptr_list.h. // // Create a typedef for the type with typedef VPTR(type) PTR_type; // When using a VPTR, replace Class* with PTR_Class. // // ----- Specific Macros: // // PTR_TO_TADDR(ptr) // Retrieves the raw target address for a ?PTR. // See code:dac_cast for the preferred alternative // // PTR_HOST_TO_TADDR(host) // Given a host address of an instance produced by a ?PTR reference, // return the original target address. The host address must // be an exact match for an instance. // See code:dac_cast for the preferred alternative // // PTR_HOST_INT_TO_TADDR(host) // Given a host address which resides somewhere within an instance // produced by a ?PTR reference (a host interior pointer) return the // corresponding target address. This is useful for evaluating // relative pointers (e.g. RelativePointer<T>) where calculating the // target address requires knowledge of the target address of the // relative pointer field itself. This lookup is slower than that for // a non-interior host pointer so use it sparingly. // // VPTR_HOST_VTABLE_TO_TADDR(host) // Given the host vtable pointer for a known VPTR class, return // the target vtable pointer. // // PTR_HOST_MEMBER_TADDR(type, host, memb) // Retrieves the target address of a host instance pointer and // offsets it by the given member's offset within the type. // // PTR_HOST_INT_MEMBER_TADDR(type, host, memb) // As above but will work for interior host pointers (see the // description of PTR_HOST_INT_TO_TADDR for an explanation of host // interior pointers). // // PTR_READ(addr, size) // Reads a block of memory from the target and returns a host // pointer for it. Useful for reading blocks of data from the target // whose size is only known at runtime, such as raw code for a jitted // method. If the data being read is actually an object, use SPTR // instead to get better type semantics. // // DAC_EMPTY() // DAC_EMPTY_ERR() // DAC_EMPTY_RET(retVal) // DAC_UNEXPECTED() // Provides an empty method implementation when compiled // for DACCESS_COMPILE. For example, use to stub out methods needed // for vtable entries but otherwise unused. // // These macros are designed to turn into normal code when compiled // without DACCESS_COMPILE. // //***************************************************************************** // See code:EEStartup#TableOfContents for EE overview #ifndef __daccess_h__ #define __daccess_h__ #ifndef __in #include <specstrings.h> #endif #define DACCESS_TABLE_RESOURCE L"COREXTERNALDATAACCESSRESOURCE" #include "type_traits.hpp" #ifdef DACCESS_COMPILE #include "safemath.h" #if defined(TARGET_AMD64) || defined(TARGET_ARM64) typedef uint64_t UIntTarget; #elif defined(TARGET_X86) typedef uint32_t UIntTarget; #elif defined(TARGET_ARM) typedef uint32_t UIntTarget; #else #error unexpected target architecture #endif // // This version of things wraps pointer access in // templates which understand how to retrieve data // through an access layer. In this case no assumptions // can be made that the current compilation processor or // pointer types match the target's processor or pointer types. // // Define TADDR as a non-pointer value so use of it as a pointer // will not work properly. Define it as unsigned so // pointer comparisons aren't affected by sign. // This requires special casting to ULONG64 to sign-extend if necessary. // XXX drewb - Cheating right now by not supporting cross-plat. typedef UIntTarget TADDR; // TSIZE_T used for counts or ranges that need to span the size of a // target pointer. For cross-plat, this may be different than SIZE_T // which reflects the host pointer size. typedef UIntTarget TSIZE_T; // Information stored in the DAC table of interest to the DAC implementation // Note that this information is shared between all instantiations of ClrDataAccess, so initialize // it just once in code:ClrDataAccess.GetDacGlobals (rather than use fields in ClrDataAccess); struct DacTableInfo { // On Windows, the first DWORD is the 32-bit timestamp read out of the runtime dll's debug directory. // The remaining 3 DWORDS must all be 0. // On Mac, this is the 16-byte UUID of the runtime dll. // It is used to validate that mscorwks is the same version as mscordacwks uint32_t dwID0; uint32_t dwID1; uint32_t dwID2; uint32_t dwID3; }; extern DacTableInfo g_dacTableInfo; // // The following table contains all the global information that data access needs to begin // operation. All of the values stored here are RVAs. DacGlobalBase() returns the current // base address to combine with to get a full target address. // typedef struct _DacGlobals { // These will define all of the dac related mscorwks static and global variables // TODO: update DacTableGen to parse "uint32_t" instead of "ULONG32" for the ids #ifdef DAC_CLR_ENVIRONMENT #define DEFINE_DACVAR(id_type, size, id) id_type id; #define DEFINE_DACVAR_NO_DUMP(id_type, size, id) id_type id; #else #define DEFINE_DACVAR(id_type, size, id) uint32_t id; #define DEFINE_DACVAR_NO_DUMP(id_type, size, id) uint32_t id; #endif #include "dacvars.h" #undef DEFINE_DACVAR_NO_DUMP #undef DEFINE_DACVAR /* // Global functions. ULONG fn__QueueUserWorkItemCallback; ULONG fn__ThreadpoolMgr__AsyncCallbackCompletion; ULONG fn__ThreadpoolMgr__AsyncTimerCallbackCompletion; ULONG fn__DACNotifyCompilationFinished; #ifdef HOST_X86 ULONG fn__NativeDelayFixupAsmStub; ULONG fn__NativeDelayFixupAsmStubRet; #endif // HOST_X86 ULONG fn__PInvokeCalliReturnFromCall; ULONG fn__NDirectGenericStubReturnFromCall; ULONG fn__DllImportForDelegateGenericStubReturnFromCall; */ } DacGlobals; extern DacGlobals g_dacGlobals; #ifdef __cplusplus extern "C" { #endif // These two functions are largely just for marking code // that is not fully converted. DacWarning prints a debug // message, while DacNotImpl throws a not-implemented exception. void __cdecl DacWarning(_In_ _In_z_ char* format, ...); void DacNotImpl(void); void DacError(HRESULT err); void __declspec(noreturn) DacError_NoRet(HRESULT err); TADDR DacGlobalBase(void); HRESULT DacReadAll(TADDR addr, void* buffer, uint32_t size, bool throwEx); #ifdef DAC_CLR_ENVIRONMENT HRESULT DacWriteAll(TADDR addr, PVOID buffer, ULONG32 size, bool throwEx); HRESULT DacAllocVirtual(TADDR addr, ULONG32 size, ULONG32 typeFlags, ULONG32 protectFlags, bool throwEx, TADDR* mem); HRESULT DacFreeVirtual(TADDR mem, ULONG32 size, ULONG32 typeFlags, bool throwEx); #endif // DAC_CLR_ENVIRONMENT /* We are simulating a tiny bit of memory existing in the debuggee address space that really isn't there. The memory appears to exist in the last 1KB of the memory space to make minimal risk that it collides with any legitimate debuggee memory. When the DAC uses DacInstantiateTypeByAddressHelper on these high addresses instead of getting back a pointer in the DAC_INSTANCE cache it will get back a pointer to specifically configured block of debugger memory. Rationale: This method was invented to solve a problem when doing stack walking in the DAC. When running in-process the register context has always been written to memory somewhere before the stackwalker begins to operate. The stackwalker doesn't track the registers themselves, but rather the storage locations where registers were written. When the DAC runs the registers haven't been saved anywhere - there is no memory address that refers to them. It would be easy to store the registers in the debugger's memory space but the Regdisplay is typed as PTR_UIntNative, not uintptr_t*. We could change REGDISPLAY to point at debugger local addresses, but then we would have the opposite problem, being unable to refer to stack addresses that are in the debuggee memory space. Options we could do: 1) Add discriminant bits to REGDISPLAY fields to record whether the pointer is local or remote a) Do it in the runtime definition - adds size and complexity to mrt100 for a debug only scenario b) Do it only in the DAC definition - breaks marshalling for types that are or contain REGDISPLAY (ie StackFrameIterator). 2) Add a new DebuggerREGDISPLAY type that can hold local or remote addresses, and then create parallel DAC stackwalking code that uses it. This is a bunch of work and has higher maintenance cost to keep both code paths operational and functionally identical. 3) Allocate space in debuggee that will be used to stash the registers when doing a debug stackwalk - increases runtime working set for debug only scenario and won't work for dumps 4) Same as #3, but don't actually allocate the space at runtime, just simulate that it was allocated within the debugger - risk of colliding with real runtime allocations, adds complexity to the DAC. #4 seems the best option to me, so we wound up here. */ // This address is picked to be very unlikely to collide with any real memory usage in the target #define SIMULATED_DEBUGGEE_MEMORY_BASE_ADDRESS ((TADDR) -1024) // The byte at ((TADDR)-1) isn't addressable at all, so we only have 1023 bytes of usable space // At the moment we only need 256 bytes at most. #define SIMULATED_DEBUGGEE_MEMORY_MAX_SIZE 1023 // Sets the simulated debuggee memory region, or clears it if pSimulatedDebuggeeMemory = NULL // See large comment above for more details. void SetSimulatedDebuggeeMemory(void* pSimulatedDebuggeeMemory, uint32_t cbSimulatedDebuggeeMemory); void* DacInstantiateTypeByAddress(TADDR addr, uint32_t size, bool throwEx); void* DacInstantiateTypeByAddressNoReport(TADDR addr, uint32_t size, bool throwEx); void* DacInstantiateClassByVTable(TADDR addr, uint32_t minSize, bool throwEx); // This method should not be used casually. Make sure simulatedTargetAddr does not cause collisions. See comment in dacfn.cpp for more details. void* DacInstantiateTypeAtSimulatedAddress(TADDR simulatedTargetAddr, uint32_t size, void* pLocalBuffer, bool throwEx); // Copy a null-terminated ascii or unicode string from the target to the host. // Note that most of the work here is to find the null terminator. If you know the exact length, // then you can also just call DacInstantiateTypebyAddress. char* DacInstantiateStringA(TADDR addr, uint32_t maxChars, bool throwEx); wchar_t* DacInstantiateStringW(TADDR addr, uint32_t maxChars, bool throwEx); TADDR DacGetTargetAddrForHostAddr(const void* ptr, bool throwEx); TADDR DacGetTargetAddrForHostInteriorAddr(const void* ptr, bool throwEx); TADDR DacGetTargetVtForHostVt(const void* vtHost, bool throwEx); wchar_t* DacGetVtNameW(TADDR targetVtable); // Report a region of memory to the debugger void DacEnumMemoryRegion(TADDR addr, TSIZE_T size, bool fExpectSuccess = true); HRESULT DacWriteHostInstance(void * host, bool throwEx); #ifdef DAC_CLR_ENVIRONMENT // Occasionally it's necessary to allocate some host memory for // instance data that's created on the fly and so doesn't directly // correspond to target memory. These are held and freed on flush // like other instances but can't be looked up by address. PVOID DacAllocHostOnlyInstance(ULONG32 size, bool throwEx); // Determines whether ASSERTs should be raised when inconsistencies in the target are detected bool DacTargetConsistencyAssertsEnabled(); // Host instances can be marked as they are enumerated in // order to break cycles. This function returns true if // the instance is already marked, otherwise it marks the // instance and returns false. bool DacHostPtrHasEnumMark(LPCVOID host); // Determines if EnumMemoryRegions has been called on a method descriptor. // This helps perf for minidumps of apps with large managed stacks. bool DacHasMethodDescBeenEnumerated(LPCVOID pMD); // Sets a flag indicating that EnumMemoryRegions on a method desciptor // has been successfully called. The function returns true if // this flag had been previously set. bool DacSetMethodDescEnumerated(LPCVOID pMD); // Determines if a method descriptor is valid BOOL DacValidateMD(LPCVOID pMD); // Enumerate the instructions around a call site to help debugger stack walking heuristics void DacEnumCodeForStackwalk(TADDR taCallEnd); // Given the address and the size of a memory range which is stored in the buffer, replace all the patches // in the buffer with the real opcodes. This is especially important on X64 where the unwinder needs to // disassemble the native instructions. class MemoryRange; HRESULT DacReplacePatchesInHostMemory(MemoryRange range, PVOID pBuffer); // // Convenience macros for EnumMemoryRegions implementations. // // Enumerate the given host instance and return // true if the instance hasn't already been enumerated. #define DacEnumHostDPtrMem(host) \ (!DacHostPtrHasEnumMark(host) ? \ (DacEnumMemoryRegion(PTR_HOST_TO_TADDR(host), sizeof(*host)), \ true) : false) #define DacEnumHostSPtrMem(host, type) \ (!DacHostPtrHasEnumMark(host) ? \ (DacEnumMemoryRegion(PTR_HOST_TO_TADDR(host), \ type::DacSize(PTR_HOST_TO_TADDR(host))), \ true) : false) #define DacEnumHostVPtrMem(host) \ (!DacHostPtrHasEnumMark(host) ? \ (DacEnumMemoryRegion(PTR_HOST_TO_TADDR(host), (host)->VPtrSize()), \ true) : false) // Check enumeration of 'this' and return if this has already been // enumerated. Making this the first line of an object's EnumMemoryRegions // method will prevent cycles. #define DAC_CHECK_ENUM_THIS() \ if (DacHostPtrHasEnumMark(this)) return #define DAC_ENUM_DTHIS() \ if (!DacEnumHostDPtrMem(this)) return #define DAC_ENUM_STHIS(type) \ if (!DacEnumHostSPtrMem(this, type)) return #define DAC_ENUM_VTHIS() \ if (!DacEnumHostVPtrMem(this)) return #endif // DAC_CLR_ENVIRONMENT #ifdef __cplusplus } // // Computes (taBase + (dwIndex * dwElementSize()), with overflow checks. // // Arguments: // taBase the base TADDR value // dwIndex the index of the offset // dwElementSize the size of each element (to multiply the offset by) // // Return value: // The resulting TADDR, or throws CORDB_E_TARGET_INCONSISTENT on overlow. // // Notes: // The idea here is that overflows during address arithmetic suggest that we're operating on corrupt // pointers. It helps to improve reliability to detect the cases we can (like overflow) and fail. Note // that this is just a heuristic, not a security measure. We can't trust target data regardless - // failing on overflow is just one easy case of corruption to detect. There is no need to use checked // arithmetic everywhere in the DAC infrastructure, this is intended just for the places most likely to // help catch bugs (eg. __DPtr::operator[]). // inline TADDR DacTAddrOffset( TADDR taBase, TSIZE_T dwIndex, TSIZE_T dwElementSize ) { #ifdef DAC_CLR_ENVIRONMENT ClrSafeInt<TADDR> t(taBase); t += ClrSafeInt<TSIZE_T>(dwIndex) * ClrSafeInt<TSIZE_T>(dwElementSize); if( t.IsOverflow() ) { // Pointer arithmetic overflow - probably due to corrupt target data //DacError(CORDBG_E_TARGET_INCONSISTENT); DacError(E_FAIL); } return t.Value(); #else // TODO: port safe math return taBase + (dwIndex*dwElementSize); #endif } // Base pointer wrapper which provides common behavior. class __TPtrBase { public: __TPtrBase() { // Make uninitialized pointers obvious. m_addr = (TADDR)-1; } explicit __TPtrBase(TADDR addr) { m_addr = addr; } bool operator!() const { return m_addr == 0; } // We'd like to have an implicit conversion to bool here since the C++ // standard says all pointer types are implicitly converted to bool. // Unfortunately, that would cause ambiguous overload errors for uses // of operator== and operator!=. Instead callers will have to compare // directly against NULL. bool operator==(TADDR addr) const { return m_addr == addr; } bool operator!=(TADDR addr) const { return m_addr != addr; } bool operator<(TADDR addr) const { return m_addr < addr; } bool operator>(TADDR addr) const { return m_addr > addr; } bool operator<=(TADDR addr) const { return m_addr <= addr; } bool operator>=(TADDR addr) const { return m_addr >= addr; } TADDR GetAddr(void) const { return m_addr; } TADDR SetAddr(TADDR addr) { m_addr = addr; return addr; } protected: TADDR m_addr; }; // Adds comparison operations // Its possible we just want to merge these into __TPtrBase, but SPtr isn't comparable with // other types right now and I would rather stay conservative class __ComparableTPtrBase : public __TPtrBase { protected: __ComparableTPtrBase(void) : __TPtrBase() {} explicit __ComparableTPtrBase(TADDR addr) : __TPtrBase(addr) {} public: bool operator==(const __ComparableTPtrBase& ptr) const { return m_addr == ptr.m_addr; } bool operator!=(const __ComparableTPtrBase& ptr) const { return !operator==(ptr); } bool operator<(const __ComparableTPtrBase& ptr) const { return m_addr < ptr.m_addr; } bool operator>(const __ComparableTPtrBase& ptr) const { return m_addr > ptr.m_addr; } bool operator<=(const __ComparableTPtrBase& ptr) const { return m_addr <= ptr.m_addr; } bool operator>=(const __ComparableTPtrBase& ptr) const { return m_addr >= ptr.m_addr; } }; // Pointer wrapper base class for various forms of normal data. // This has the common functionality between __DPtr and __ArrayDPtr. // The DPtrType type parameter is the actual derived type in use. This is necessary so that // inhereted functions preserve exact return types. template<typename type, typename DPtrType> class __DPtrBase : public __ComparableTPtrBase { public: typedef type _Type; typedef type* _Ptr; protected: // Constructors // All protected - this type should not be used directly - use one of the derived types instead. __DPtrBase< type, DPtrType >(void) : __ComparableTPtrBase() {} explicit __DPtrBase< type, DPtrType >(TADDR addr) : __ComparableTPtrBase(addr) {} explicit __DPtrBase(__TPtrBase addr) { m_addr = addr.GetAddr(); } explicit __DPtrBase(type const * host) { m_addr = DacGetTargetAddrForHostAddr(host, true); } public: DPtrType& operator=(const __TPtrBase& ptr) { m_addr = ptr.GetAddr(); return DPtrType(m_addr); } DPtrType& operator=(TADDR addr) { m_addr = addr; return DPtrType(m_addr); } type& operator*(void) const { return *(type*)DacInstantiateTypeByAddress(m_addr, sizeof(type), true); } using __ComparableTPtrBase::operator==; using __ComparableTPtrBase::operator!=; using __ComparableTPtrBase::operator<; using __ComparableTPtrBase::operator>; using __ComparableTPtrBase::operator<=; using __ComparableTPtrBase::operator>=; bool operator==(TADDR addr) const { return m_addr == addr; } bool operator!=(TADDR addr) const { return m_addr != addr; } // Array index operator // we want an operator[] for all possible numeric types (rather than rely on // implicit numeric conversions on the argument) to prevent ambiguity with // DPtr's implicit conversion to type* and the built-in operator[]. // @dbgtodo rbyers: we could also use this technique to simplify other operators below. template<typename indexType> type& operator[](indexType index) { // Compute the address of the element. TADDR elementAddr; if( index >= 0 ) { elementAddr = DacTAddrOffset(m_addr, index, sizeof(type)); } else { // Don't bother trying to do overflow checking for negative indexes - they are rare compared to // positive ones. ClrSafeInt doesn't support signed datatypes yet (although we should be able to add it // pretty easily). elementAddr = m_addr + index * sizeof(type); } // Marshal over a single instance and return a reference to it. return *(type*) DacInstantiateTypeByAddress(elementAddr, sizeof(type), true); } template<typename indexType> type const & operator[](indexType index) const { return (*const_cast<__DPtrBase*>(this))[index]; } //------------------------------------------------------------------------- // operator+ DPtrType operator+(unsigned short val) { return DPtrType(DacTAddrOffset(m_addr, val, sizeof(type))); } DPtrType operator+(short val) { return DPtrType(m_addr + val * sizeof(type)); } // size_t is unsigned int on Win32, so we need // to ifdef here to make sure the unsigned int // and size_t overloads don't collide. size_t // is marked __w64 so a simple unsigned int // will not work on Win32, it has to be size_t. DPtrType operator+(size_t val) { return DPtrType(DacTAddrOffset(m_addr, val, sizeof(type))); } #if (!defined (HOST_X86) && !defined(_SPARC_) && !defined(HOST_ARM)) || (defined(HOST_X86) && defined(__APPLE__)) DPtrType operator+(unsigned int val) { return DPtrType(DacTAddrOffset(m_addr, val, sizeof(type))); } #endif // (!defined (HOST_X86) && !defined(_SPARC_) && !defined(HOST_ARM)) || (defined(HOST_X86) && defined(__APPLE__)) DPtrType operator+(int val) { return DPtrType(m_addr + val * sizeof(type)); } #ifndef TARGET_UNIX // for now, everything else is 32 bit DPtrType operator+(unsigned long val) { return DPtrType(DacTAddrOffset(m_addr, val, sizeof(type))); } DPtrType operator+(long val) { return DPtrType(m_addr + val * sizeof(type)); } #endif // !TARGET_UNIX // for now, everything else is 32 bit #if !defined(HOST_ARM) && !defined(HOST_X86) DPtrType operator+(intptr_t val) { return DPtrType(m_addr + val * sizeof(type)); } #endif //------------------------------------------------------------------------- // operator- DPtrType operator-(unsigned short val) { return DPtrType(m_addr - val * sizeof(type)); } DPtrType operator-(short val) { return DPtrType(m_addr - val * sizeof(type)); } // size_t is unsigned int on Win32, so we need // to ifdef here to make sure the unsigned int // and size_t overloads don't collide. size_t // is marked __w64 so a simple unsigned int // will not work on Win32, it has to be size_t. DPtrType operator-(size_t val) { return DPtrType(m_addr - val * sizeof(type)); } DPtrType operator-(signed __int64 val) { return DPtrType(m_addr - val * sizeof(type)); } #if !defined (HOST_X86) && !defined(_SPARC_) && !defined(HOST_ARM) DPtrType operator-(unsigned int val) { return DPtrType(m_addr - val * sizeof(type)); } #endif // !defined (HOST_X86) && !defined(_SPARC_) && !defined(HOST_ARM) DPtrType operator-(int val) { return DPtrType(m_addr - val * sizeof(type)); } #ifdef _MSC_VER // for now, everything else is 32 bit DPtrType operator-(unsigned long val) { return DPtrType(m_addr - val * sizeof(type)); } DPtrType operator-(long val) { return DPtrType(m_addr - val * sizeof(type)); } #endif // _MSC_VER // for now, everything else is 32 bit size_t operator-(const DPtrType& val) { return (size_t)((m_addr - val.m_addr) / sizeof(type)); } //------------------------------------------------------------------------- DPtrType& operator+=(size_t val) { m_addr += val * sizeof(type); return static_cast<DPtrType&>(*this); } DPtrType& operator-=(size_t val) { m_addr -= val * sizeof(type); return static_cast<DPtrType&>(*this); } DPtrType& operator++() { m_addr += sizeof(type); return static_cast<DPtrType&>(*this); } DPtrType& operator--() { m_addr -= sizeof(type); return static_cast<DPtrType&>(*this); } DPtrType operator++(int postfix) { UNREFERENCED_PARAMETER(postfix); DPtrType orig = DPtrType(*this); m_addr += sizeof(type); return orig; } DPtrType operator--(int postfix) { UNREFERENCED_PARAMETER(postfix); DPtrType orig = DPtrType(*this); m_addr -= sizeof(type); return orig; } bool IsValid(void) const { return m_addr && DacInstantiateTypeByAddress(m_addr, sizeof(type), false) != NULL; } void EnumMem(void) const { DacEnumMemoryRegion(m_addr, sizeof(type)); } }; // Pointer wrapper for objects which are just plain data // and need no special handling. template<typename type> class __DPtr : public __DPtrBase<type,__DPtr<type> > { #ifdef __GNUC__ protected: //there seems to be a bug in GCC's inference logic. It can't find m_addr. using __DPtrBase<type,__DPtr<type> >::m_addr; #endif // __GNUC__ public: // constructors - all chain to __DPtrBase constructors __DPtr< type >(void) : __DPtrBase<type,__DPtr<type> >() {} __DPtr< type >(TADDR addr) : __DPtrBase<type,__DPtr<type> >(addr) {} // construct const from non-const typedef typename type_traits::remove_const<type>::type mutable_type; __DPtr< type >(__DPtr<mutable_type> const & rhs) : __DPtrBase<type,__DPtr<type> >(rhs.GetAddr()) {} explicit __DPtr< type >(__TPtrBase addr) : __DPtrBase<type,__DPtr<type> >(addr) {} explicit __DPtr< type >(type const * host) : __DPtrBase<type,__DPtr<type> >(host) {} operator type*() const { return (type*)DacInstantiateTypeByAddress(m_addr, sizeof(type), true); } type* operator->() const { return (type*)DacInstantiateTypeByAddress(m_addr, sizeof(type), true); } }; #define DPTR(type) __DPtr< type > // A restricted form of DPtr that doesn't have any conversions to pointer types. // This is useful for pointer types that almost always represent arrays, as opposed // to pointers to single instances (eg. PTR_BYTE). In these cases, allowing implicit // conversions to (for eg.) BYTE* would usually result in incorrect usage (eg. pointer // arithmetic and array indexing), since only a single instance has been marshalled to the host. // If you really must marshal a single instance (eg. converting T* to PTR_T is too painful for now), // then use code:DacUnsafeMarshalSingleElement so we can identify such unsafe code. template<typename type> class __ArrayDPtr : public __DPtrBase<type,__ArrayDPtr<type> > { public: // constructors - all chain to __DPtrBase constructors __ArrayDPtr< type >(void) : __DPtrBase<type,__ArrayDPtr<type> >() {} __ArrayDPtr< type >(TADDR addr) : __DPtrBase<type,__ArrayDPtr<type> >(addr) {} // construct const from non-const typedef typename type_traits::remove_const<type>::type mutable_type; __ArrayDPtr< type >(__ArrayDPtr<mutable_type> const & rhs) : __DPtrBase<type,__ArrayDPtr<type> >(rhs.GetAddr()) {} explicit __ArrayDPtr< type >(__TPtrBase addr) : __DPtrBase<type,__ArrayDPtr<type> >(addr) {} // Note that there is also no explicit constructor from host instances (type*). // Going this direction is less problematic, but often still represents risky coding. }; #define ArrayDPTR(type) __ArrayDPtr< type > // Pointer wrapper for objects which are just plain data // but whose size is not the same as the base type size. // This can be used for prefetching data for arrays or // for cases where an object has a variable size. template<typename type> class __SPtr : public __TPtrBase { public: typedef type _Type; typedef type* _Ptr; __SPtr< type >(void) : __TPtrBase() {} __SPtr< type >(TADDR addr) : __TPtrBase(addr) {} explicit __SPtr< type >(__TPtrBase addr) { m_addr = addr.GetAddr(); } explicit __SPtr< type >(type* host) { m_addr = DacGetTargetAddrForHostAddr(host, true); } __SPtr< type >& operator=(const __TPtrBase& ptr) { m_addr = ptr.m_addr; return *this; } __SPtr< type >& operator=(TADDR addr) { m_addr = addr; return *this; } operator type*() const { if (m_addr) { return (type*)DacInstantiateTypeByAddress(m_addr, type::DacSize(m_addr), true); } else { return (type*)NULL; } } type* operator->() const { if (m_addr) { return (type*)DacInstantiateTypeByAddress(m_addr, type::DacSize(m_addr), true); } else { return (type*)NULL; } } type& operator*(void) const { if (!m_addr) { DacError(E_INVALIDARG); } return *(type*)DacInstantiateTypeByAddress(m_addr, type::DacSize(m_addr), true); } bool IsValid(void) const { return m_addr && DacInstantiateTypeByAddress(m_addr, type::DacSize(m_addr), false) != NULL; } void EnumMem(void) const { if (m_addr) { DacEnumMemoryRegion(m_addr, type::DacSize(m_addr)); } } }; #define SPTR(type) __SPtr< type > // Pointer wrapper for objects which have a single leading // vtable, such as objects in a single-inheritance tree. // The base class of all such trees must have use // VPTR_BASE_VTABLE_CLASS in their declaration and all // instantiable members of the tree must be listed in vptr_list.h. template<class type> class __VPtr : public __TPtrBase { public: // VPtr::_Type has to be a pointer as // often the type is an abstract class. // This type is not expected to be used anyway. typedef type* _Type; typedef type* _Ptr; __VPtr< type >(void) : __TPtrBase() {} __VPtr< type >(TADDR addr) : __TPtrBase(addr) {} explicit __VPtr< type >(__TPtrBase addr) { m_addr = addr.GetAddr(); } explicit __VPtr< type >(type* host) { m_addr = DacGetTargetAddrForHostAddr(host, true); } __VPtr< type >& operator=(const __TPtrBase& ptr) { m_addr = ptr.m_addr; return *this; } __VPtr< type >& operator=(TADDR addr) { m_addr = addr; return *this; } operator type*() const { return (type*)DacInstantiateClassByVTable(m_addr, sizeof(type), true); } type* operator->() const { return (type*)DacInstantiateClassByVTable(m_addr, sizeof(type), true); } bool operator==(const __VPtr< type >& ptr) const { return m_addr == ptr.m_addr; } bool operator==(TADDR addr) const { return m_addr == addr; } bool operator!=(const __VPtr< type >& ptr) const { return !operator==(ptr); } bool operator!=(TADDR addr) const { return m_addr != addr; } bool IsValid(void) const { return m_addr && DacInstantiateClassByVTable(m_addr, sizeof(type), false) != NULL; } void EnumMem(void) const { if (IsValid()) { DacEnumMemoryRegion(m_addr, (operator->())->VPtrSize()); } } }; #define VPTR(type) __VPtr< type > // Pointer wrapper for 8-bit strings. #ifdef DAC_CLR_ENVIRONMENT template<typename type, ULONG32 maxChars = 32760> #else template<typename type, uint32_t maxChars = 32760> #endif class __Str8Ptr : public __DPtr<char> { public: typedef type _Type; typedef type* _Ptr; __Str8Ptr< type, maxChars >(void) : __DPtr<char>() {} __Str8Ptr< type, maxChars >(TADDR addr) : __DPtr<char>(addr) {} explicit __Str8Ptr< type, maxChars >(__TPtrBase addr) { m_addr = addr.GetAddr(); } explicit __Str8Ptr< type, maxChars >(type* host) { m_addr = DacGetTargetAddrForHostAddr(host, true); } __Str8Ptr< type, maxChars >& operator=(const __TPtrBase& ptr) { m_addr = ptr.m_addr; return *this; } __Str8Ptr< type, maxChars >& operator=(TADDR addr) { m_addr = addr; return *this; } operator type*() const { return (type*)DacInstantiateStringA(m_addr, maxChars, true); } bool IsValid(void) const { return m_addr && DacInstantiateStringA(m_addr, maxChars, false) != NULL; } void EnumMem(void) const { char* str = DacInstantiateStringA(m_addr, maxChars, false); if (str) { DacEnumMemoryRegion(m_addr, strlen(str) + 1); } } }; #define S8PTR(type) __Str8Ptr< type > #define S8PTRMAX(type, maxChars) __Str8Ptr< type, maxChars > // Pointer wrapper for 16-bit strings. #ifdef DAC_CLR_ENVIRONMENT template<typename type, ULONG32 maxChars = 32760> #else template<typename type, uint32_t maxChars = 32760> #endif class __Str16Ptr : public __DPtr<wchar_t> { public: typedef type _Type; typedef type* _Ptr; __Str16Ptr< type, maxChars >(void) : __DPtr<wchar_t>() {} __Str16Ptr< type, maxChars >(TADDR addr) : __DPtr<wchar_t>(addr) {} explicit __Str16Ptr< type, maxChars >(__TPtrBase addr) { m_addr = addr.GetAddr(); } explicit __Str16Ptr< type, maxChars >(type* host) { m_addr = DacGetTargetAddrForHostAddr(host, true); } __Str16Ptr< type, maxChars >& operator=(const __TPtrBase& ptr) { m_addr = ptr.m_addr; return *this; } __Str16Ptr< type, maxChars >& operator=(TADDR addr) { m_addr = addr; return *this; } operator type*() const { return (type*)DacInstantiateStringW(m_addr, maxChars, true); } bool IsValid(void) const { return m_addr && DacInstantiateStringW(m_addr, maxChars, false) != NULL; } void EnumMem(void) const { char* str = DacInstantiateStringW(m_addr, maxChars, false); if (str) { DacEnumMemoryRegion(m_addr, strlen(str) + 1); } } }; #define S16PTR(type) __Str16Ptr< type > #define S16PTRMAX(type, maxChars) __Str16Ptr< type, maxChars > template<typename type> class __GlobalVal { public: #ifdef DAC_CLR_ENVIRONMENT __GlobalVal< type >(PULONG rvaPtr) #else __GlobalVal< type >(uint32_t* rvaPtr) #endif { m_rvaPtr = rvaPtr; } operator type() const { return (type)*__DPtr< type >(DacGlobalBase() + *m_rvaPtr); } __DPtr< type > operator&() const { return __DPtr< type >(DacGlobalBase() + *m_rvaPtr); } // @dbgtodo rbyers dac support: This updates values in the host. This seems extremely dangerous // to do silently. I'd prefer that a specific (searchable) write function // was used. Try disabling this and see what fails... type & operator=(type & val) { type* ptr = __DPtr< type >(DacGlobalBase() + *m_rvaPtr); // Update the host copy; *ptr = val; // Write back to the target. DacWriteHostInstance(ptr, true); return val; } bool IsValid(void) const { return __DPtr< type >(DacGlobalBase() + *m_rvaPtr).IsValid(); } void EnumMem(void) const { TADDR p = DacGlobalBase() + *m_rvaPtr; __DPtr< type >(p).EnumMem(); } private: #ifdef DAC_CLR_ENVIRONMENT PULONG m_rvaPtr; #else uint32_t* m_rvaPtr; #endif }; template<typename type, size_t size> class __GlobalArray { public: #ifdef DAC_CLR_ENVIRONMENT __GlobalArray< type, size >(PULONG rvaPtr) #else __GlobalArray< type, size >(uint32_t* rvaPtr) #endif { m_rvaPtr = rvaPtr; } __DPtr< type > operator&() const { return __DPtr< type >(DacGlobalBase() + *m_rvaPtr); } type& operator[](unsigned int index) const { return __DPtr< type >(DacGlobalBase() + *m_rvaPtr)[index]; } bool IsValid(void) const { // Only validates the base pointer, not the full array range. return __DPtr< type >(DacGlobalBase() + *m_rvaPtr).IsValid(); } void EnumMem(void) const { DacEnumMemoryRegion(DacGlobalBase() + *m_rvaPtr, sizeof(type) * size); } private: #ifdef DAC_CLR_ENVIRONMENT PULONG m_rvaPtr; #else uint32_t* m_rvaPtr; #endif }; template<typename acc_type, typename store_type> class __GlobalPtr { public: #ifdef DAC_CLR_ENVIRONMENT __GlobalPtr< acc_type, store_type >(PULONG rvaPtr) #else __GlobalPtr< acc_type, store_type >(uint32_t* rvaPtr) #endif { m_rvaPtr = rvaPtr; } __DPtr< store_type > operator&() const { return __DPtr< store_type >(DacGlobalBase() + *m_rvaPtr); } store_type & operator=(store_type & val) { store_type* ptr = __DPtr< store_type >(DacGlobalBase() + *m_rvaPtr); // Update the host copy; *ptr = val; // Write back to the target. DacWriteHostInstance(ptr, true); return val; } acc_type operator->() const { return (acc_type)*__DPtr< store_type >(DacGlobalBase() + *m_rvaPtr); } operator acc_type() const { return (acc_type)*__DPtr< store_type >(DacGlobalBase() + *m_rvaPtr); } operator store_type() const { return *__DPtr< store_type >(DacGlobalBase() + *m_rvaPtr); } bool operator!() const { return !*__DPtr< store_type >(DacGlobalBase() + *m_rvaPtr); } typename store_type operator[](int index) const { return (*__DPtr< store_type >(DacGlobalBase() + *m_rvaPtr))[index]; } typename store_type operator[](unsigned int index) const { return (*__DPtr< store_type >(DacGlobalBase() + *m_rvaPtr))[index]; } TADDR GetAddr() const { return (*__DPtr< store_type >(DacGlobalBase() + *m_rvaPtr)).GetAddr(); } TADDR GetAddrRaw () const { return DacGlobalBase() + *m_rvaPtr; } // This is only testing the the pointer memory is available but does not verify // the memory that it points to. // bool IsValidPtr(void) const { return __DPtr< store_type >(DacGlobalBase() + *m_rvaPtr).IsValid(); } bool IsValid(void) const { return __DPtr< store_type >(DacGlobalBase() + *m_rvaPtr).IsValid() && (*__DPtr< store_type >(DacGlobalBase() + *m_rvaPtr)).IsValid(); } void EnumMem(void) const { __DPtr< store_type > ptr(DacGlobalBase() + *m_rvaPtr); ptr.EnumMem(); if (ptr.IsValid()) { (*ptr).EnumMem(); } } #ifdef DAC_CLR_ENVIRONMENT PULONG m_rvaPtr; #else uint32_t* m_rvaPtr; #endif }; template<typename acc_type, typename store_type> inline bool operator==(const __GlobalPtr<acc_type, store_type>& gptr, acc_type host) { return DacGetTargetAddrForHostAddr(host, true) == *__DPtr< TADDR >(DacGlobalBase() + *gptr.m_rvaPtr); } template<typename acc_type, typename store_type> inline bool operator!=(const __GlobalPtr<acc_type, store_type>& gptr, acc_type host) { return !operator==(gptr, host); } template<typename acc_type, typename store_type> inline bool operator==(acc_type host, const __GlobalPtr<acc_type, store_type>& gptr) { return DacGetTargetAddrForHostAddr(host, true) == *__DPtr< TADDR >(DacGlobalBase() + *gptr.m_rvaPtr); } template<typename acc_type, typename store_type> inline bool operator!=(acc_type host, const __GlobalPtr<acc_type, store_type>& gptr) { return !operator==(host, gptr); } // // __VoidPtr is a type that behaves like void* but for target pointers. // Behavior of PTR_VOID: // * has void* semantics. Will compile to void* in non-DAC builds (just like // other PTR types. Unlike TADDR, we want pointer semantics. // * NOT assignable from host pointer types or convertible to host pointer // types - ensures we can't confuse host and target pointers (we'll get // compiler errors if we try and cast between them). // * like void*, no pointer arithmetic or dereferencing is allowed // * like TADDR, can be used to construct any __DPtr / __VPtr instance // * representation is the same as a void* (for marshalling / casting) // // One way in which __VoidPtr is unlike void* is that it can't be cast to // pointer or integer types. On the one hand, this is a good thing as it forces // us to keep target pointers separate from other data types. On the other hand // in practice this means we have to use dac_cast<TADDR> in places where we used // to use a (TADDR) cast. Unfortunately C++ provides us no way to allow the // explicit cast to primitive types without also allowing implicit conversions. // // This is very similar in spirit to TADDR. The primary difference is that // PTR_VOID has pointer semantics, where TADDR has integer semantics. When // dacizing uses of void* to TADDR, casts must be inserted everywhere back to // pointer types. If we switch a use of TADDR to PTR_VOID, those casts in // DACCESS_COMPILE regions no longer compile (see above). Also, TADDR supports // pointer arithmetic, but that might not be necessary (could use PTR_BYTE // instead etc.). Ideally we'd probably have just one type for this purpose // (named TADDR but with the semantics of PTR_VOID), but outright conversion // would require too much work. // template <> class __DPtr<void> : public __ComparableTPtrBase { public: __DPtr(void) : __ComparableTPtrBase() {} __DPtr(TADDR addr) : __ComparableTPtrBase(addr) {} // Note, unlike __DPtr, this ctor form is not explicit. We allow implicit // conversions from any pointer type (just like for void*). __DPtr(__TPtrBase addr) { m_addr = addr.GetAddr(); } // Like TPtrBase, VoidPtrs can also be created impicitly from all GlobalPtrs template<typename acc_type, typename store_type> __DPtr(__GlobalPtr<acc_type, store_type> globalPtr) { m_addr = globalPtr.GetAddr(); } // Note, unlike __DPtr, there is no explicit conversion from host pointer // types. Since void* cannot be marshalled, there is no such thing as // a void* DAC instance in the host. // Also, we don't want an implicit conversion to TADDR because then the // compiler will allow pointer arithmetic (which it wouldn't allow for // void*). Instead, callers can use dac_cast<TADDR> if they want. // Note, unlike __DPtr, any pointer type can be assigned to a __DPtr // This is to mirror the assignability of any pointer type to a void* __DPtr& operator=(const __TPtrBase& ptr) { m_addr = ptr.GetAddr(); return *this; } __DPtr& operator=(TADDR addr) { m_addr = addr; return *this; } // note, no marshalling operators (type* conversion, operator ->, operator*) // A void* can't be marshalled because we don't know how much to copy // PTR_Void can be compared to any other pointer type (because conceptually, // any other pointer type should be implicitly convertible to void*) using __ComparableTPtrBase::operator==; using __ComparableTPtrBase::operator!=; using __ComparableTPtrBase::operator<; using __ComparableTPtrBase::operator>; using __ComparableTPtrBase::operator<=; using __ComparableTPtrBase::operator>=; bool operator==(TADDR addr) const { return m_addr == addr; } bool operator!=(TADDR addr) const { return m_addr != addr; } }; typedef __DPtr<void> __VoidPtr; typedef __VoidPtr PTR_VOID; typedef DPTR(PTR_VOID) PTR_PTR_VOID; // For now we treat pointers to const and non-const void the same in DAC // builds. In general, DAC is read-only anyway and so there isn't a danger of // writing to these pointers. Also, the non-dac builds will ensure // const-correctness. However, if we wanted to support true void* / const void* // behavior, we could probably build the follow functionality by templating // __VoidPtr: // * A PTR_VOID would be implicitly convertable to PTR_CVOID // * An explicit coercion (ideally const_cast) would be required to convert a // PTR_CVOID to a PTR_VOID // * Similarily, an explicit coercion would be required to convert a cost PTR // type (eg. PTR_CBYTE) to a PTR_VOID. typedef __VoidPtr PTR_CVOID; // The special empty ctor declared here allows the whole // class hierarchy to be instantiated easily by the // external access code. The actual class body will be // read externally so no members should be initialized. // Safe access for retrieving the target address of a PTR. #define PTR_TO_TADDR(ptr) ((ptr).GetAddr()) #define GFN_TADDR(name) (DacGlobalBase() + g_dacGlobals.fn__ ## name) // ROTORTODO - g++ 3 doesn't like the use of the operator& in __GlobalVal // here. Putting GVAL_ADDR in to get things to compile while I discuss // this matter with the g++ authors. #define GVAL_ADDR(g) \ ((g).operator&()) // // References to class static and global data. // These all need to be redirected through the global // data table. // #define _SPTR_DECL(acc_type, store_type, var) \ static __GlobalPtr< acc_type, store_type > var #define _SPTR_IMPL(acc_type, store_type, cls, var) \ __GlobalPtr< acc_type, store_type > cls::var(&g_dacGlobals.cls##__##var) #define _SPTR_IMPL_INIT(acc_type, store_type, cls, var, init) \ __GlobalPtr< acc_type, store_type > cls::var(&g_dacGlobals.cls##__##var) #define _SPTR_IMPL_NS(acc_type, store_type, ns, cls, var) \ __GlobalPtr< acc_type, store_type > cls::var(&g_dacGlobals.ns##__##cls##__##var) #define _SPTR_IMPL_NS_INIT(acc_type, store_type, ns, cls, var, init) \ __GlobalPtr< acc_type, store_type > cls::var(&g_dacGlobals.ns##__##cls##__##var) #define _GPTR_DECL(acc_type, store_type, var) \ extern __GlobalPtr< acc_type, store_type > var #define _GPTR_IMPL(acc_type, store_type, var) \ __GlobalPtr< acc_type, store_type > var(&g_dacGlobals.dac__##var) #define _GPTR_IMPL_INIT(acc_type, store_type, var, init) \ __GlobalPtr< acc_type, store_type > var(&g_dacGlobals.dac__##var) #define SVAL_DECL(type, var) \ static __GlobalVal< type > var #define SVAL_IMPL(type, cls, var) \ __GlobalVal< type > cls::var(&g_dacGlobals.cls##__##var) #define SVAL_IMPL_INIT(type, cls, var, init) \ __GlobalVal< type > cls::var(&g_dacGlobals.cls##__##var) #define SVAL_IMPL_NS(type, ns, cls, var) \ __GlobalVal< type > cls::var(&g_dacGlobals.ns##__##cls##__##var) #define SVAL_IMPL_NS_INIT(type, ns, cls, var, init) \ __GlobalVal< type > cls::var(&g_dacGlobals.ns##__##cls##__##var) #define GVAL_DECL(type, var) \ extern __GlobalVal< type > var #define GVAL_IMPL(type, var) \ __GlobalVal< type > var(&g_dacGlobals.dac__##var) #define GVAL_IMPL_INIT(type, var, init) \ __GlobalVal< type > var(&g_dacGlobals.dac__##var) #define GARY_DECL(type, var, size) \ extern __GlobalArray< type, size > var #define GARY_IMPL(type, var, size) \ __GlobalArray< type, size > var(&g_dacGlobals.dac__##var) // Translation from a host pointer back to the target address // that was used to retrieve the data for the host pointer. #define PTR_HOST_TO_TADDR(host) DacGetTargetAddrForHostAddr(host, true) // Translation from a host interior pointer back to the corresponding // target address. The host address must reside within a previously // retrieved instance. #define PTR_HOST_INT_TO_TADDR(host) DacGetTargetAddrForHostInteriorAddr(host, true) // Construct a pointer to a member of the given type. #define PTR_HOST_MEMBER_TADDR(type, host, memb) \ (PTR_HOST_TO_TADDR(host) + (TADDR)offsetof(type, memb)) // in the DAC build this is still typed TADDR, but in the runtime // build it preserves the member type. #define PTR_HOST_MEMBER(type, host, memb) \ (PTR_HOST_TO_TADDR(host) + (TADDR)offsetof(type, memb)) // Construct a pointer to a member of the given type given an interior // host address. #define PTR_HOST_INT_MEMBER_TADDR(type, host, memb) \ (PTR_HOST_INT_TO_TADDR(host) + (TADDR)offsetof(type, memb)) #define PTR_TO_MEMBER_TADDR(type, ptr, memb) \ (PTR_TO_TADDR(ptr) + (TADDR)offsetof(type, memb)) // in the DAC build this is still typed TADDR, but in the runtime // build it preserves the member type. #define PTR_TO_MEMBER(type, ptr, memb) \ (PTR_TO_TADDR(ptr) + (TADDR)offsetof(type, memb)) // Constructs an arbitrary data instance for a piece of // memory in the target. #define PTR_READ(addr, size) \ DacInstantiateTypeByAddress(addr, size, true) // This value is used to initialize target pointers to NULL. We want this to be TADDR type // (as opposed to, say, __TPtrBase) so that it can be used in the non-explicit ctor overloads, // eg. as an argument default value. // We can't always just use NULL because that's 0 which (in C++) can be any integer or pointer // type (causing an ambiguous overload compiler error when used in explicit ctor forms). #define PTR_NULL ((TADDR)0) // Provides an empty method implementation when compiled // for DACCESS_COMPILE. For example, use to stub out methods needed // for vtable entries but otherwise unused. // Note that these functions are explicitly NOT marked SUPPORTS_DAC so that we'll get a // DacCop warning if any calls to them are detected. // @dbgtodo rbyers: It's probably almost always wrong to call any such function, so // we should probably throw a better error (DacNotImpl), and ideally mark the function // DECLSPEC_NORETURN so we don't have to deal with fabricating return values and we can // get compiler warnings (unreachable code) anytime functions marked this way are called. #define DAC_EMPTY() { LEAF_CONTRACT; } #define DAC_EMPTY_ERR() { LEAF_CONTRACT; DacError(E_UNEXPECTED); } #define DAC_EMPTY_RET(retVal) { LEAF_CONTRACT; DacError(E_UNEXPECTED); return retVal; } #define DAC_UNEXPECTED() { LEAF_CONTRACT; DacError_NoRet(E_UNEXPECTED); } #endif // __cplusplus HRESULT DacGetTargetAddrForHostAddr(const void* ptr, TADDR * pTADDR); // Implementation details for dac_cast, should never be accessed directly. // See code:dac_cast for details and discussion. namespace dac_imp { //--------------------------------------------- // Conversion to TADDR // Forward declarations. template <typename> struct conversionHelper; template <typename T> TADDR getTaddr(T&& val); // Helper structs to get the target address of specific types // This non-specialized struct handles all instances of asTADDR that don't // take partially-specialized arguments. template <typename T> struct conversionHelper { inline static TADDR asTADDR(__TPtrBase const & tptr) { return PTR_TO_TADDR(tptr); } inline static TADDR asTADDR(TADDR addr) { return addr; } }; // Handles template <typename TypeT> struct conversionHelper<TypeT * &> { inline static TADDR asTADDR(TypeT * src) { TADDR addr = 0; if (DacGetTargetAddrForHostAddr(src, &addr) != S_OK) addr = DacGetTargetAddrForHostInteriorAddr(src, true); return addr; } }; template<typename acc_type, typename store_type> struct conversionHelper<__GlobalPtr<acc_type, store_type> const & > { inline static TADDR asTADDR(__GlobalPtr<acc_type, store_type> const & gptr) { return PTR_TO_TADDR(gptr); } }; // It is an error to try dac_cast on a __GlobalVal or a __GlobalArray. template<typename TypeT> struct conversionHelper< __GlobalVal<TypeT> const & > { inline static TADDR asTADDR(__GlobalVal<TypeT> const & gval) { static_assert(false, "Cannot use dac_cast on a __GlobalVal; first you must get its address using the '&' operator."); } }; template<typename TypeT, size_t size> struct conversionHelper< __GlobalArray<TypeT, size> const & > { inline static TADDR asTADDR(__GlobalArray<TypeT, size> const & garr) { static_assert(false, "Cannot use dac_cast on a __GlobalArray; first you must get its address using the '&' operator."); } }; // This is the main helper function, and it delegates to the above helper functions. // NOTE: this works because of C++0x reference collapsing rules for rvalue reference // arguments in template functions. template <typename T> TADDR getTaddr(T&& val) { return conversionHelper<T>::asTADDR(val); } //--------------------------------------------- // Conversion to DAC instance // Helper class to instantiate DAC instances from a TADDR // The default implementation assumes we want to create an instance of a PTR type template <typename T> struct makeDacInst { // First constructing a __TPtrBase and then constructing the target type // ensures that the target type can construct itself from a __TPtrBase. // This also prevents unknown user conversions from producing incorrect // results (since __TPtrBase can only be constructed from TADDR values). static inline T fromTaddr(TADDR addr) { return T(__TPtrBase(addr)); } }; // Specialization for creating TADDRs from TADDRs. template<> struct makeDacInst<TADDR> { static inline TADDR fromTaddr(TADDR addr) { return addr; } }; // Partial specialization for creating host instances. template <typename T> struct makeDacInst<T *> { static inline T * fromTaddr(TADDR addr) { return makeDacInst<DPTR(T)>::fromTaddr(addr); } }; /* struct Yes { char c[2]; }; struct No { char c; }; Yes& HasTPtrBase(__TPtrBase const *, ); No& HasTPtrBase(...); template <typename T> typename rh::std::enable_if< sizeof(HasTPtrBase(typename rh::std::remove_reference<T>::type *)) == sizeof(Yes), T>::type makeDacInst(TADDR addr) */ } // namespace dac_imp // DacCop in-line exclusion mechanism // Warnings - official home is DacCop\Shared\Warnings.cs, but we want a way for users to indicate // warning codes in a way that is descriptive to readers (not just code numbers). The names here // don't matter - DacCop just looks at the value enum DacCopWarningCode { // General Rules FieldAccess = 1, PointerArith = 2, PointerComparison = 3, InconsistentMarshalling = 4, CastBetweenAddressSpaces = 5, CastOfMarshalledType = 6, VirtualCallToNonVPtr = 7, UndacizedGlobalVariable = 8, // Function graph related CallUnknown = 701, CallNonDac = 702, CallVirtualUnknown = 704, CallVirtualNonDac = 705, }; // DACCOP_IGNORE is a mechanism to suppress DacCop violations from within the source-code. // See the DacCop wiki for guidance on how best to use this: http://mswikis/clr/dev/Pages/DacCop.aspx // // DACCOP_IGNORE will suppress a DacCop violation for the following (non-compound) statement. // For example: // // The "dual-mode DAC problem" occurs in a few places where a class is used both // // in the host, and marshalled from the target ... <further details> // DACCOP_IGNORE(CastBetweenAddressSpaces,"SBuffer has the dual-mode DAC problem"); // TADDR bufAddr = (TADDR)m_buffer; // // A call to DACCOP_IGNORE must occur as it's own statement, and can apply only to following // single-statements (not to compound statement blocks). Occasionally it is necessary to hoist // violation-inducing code out to its own statement (e.g., if it occurs in the conditional of an // if). // // Arguments: // code: a literal value from DacCopWarningCode indicating which violation should be suppressed. // szReasonString: a short description of why this exclusion is necessary. This is intended just // to help readers of the code understand the source of the problem, and what would be required // to fix it. More details can be provided in comments if desired. // inline void DACCOP_IGNORE(DacCopWarningCode code, const char * szReasonString) { UNREFERENCED_PARAMETER(code); UNREFERENCED_PARAMETER(szReasonString); // DacCop detects calls to this function. No implementation is necessary. } #else // !DACCESS_COMPILE // // This version of the macros turns into normal pointers // for unmodified in-proc compilation. // ******************************************************* // !!!!!!!!!!!!!!!!!!!!!!!!!NOTE!!!!!!!!!!!!!!!!!!!!!!!!!! // // Please search this file for the type name to find the // DAC versions of these definitions // // !!!!!!!!!!!!!!!!!!!!!!!!!NOTE!!!!!!!!!!!!!!!!!!!!!!!!!! // ******************************************************* // Declare TADDR as a non-pointer type so that arithmetic // can be done on it directly, as with the DACCESS_COMPILE definition. // This also helps expose pointer usage that may need to be changed. typedef uintptr_t TADDR; typedef void* PTR_VOID; typedef void** PTR_PTR_VOID; #define DPTR(type) type* #define ArrayDPTR(type) type* #define SPTR(type) type* #define VPTR(type) type* #define S8PTR(type) type* #define S8PTRMAX(type, maxChars) type* #define S16PTR(type) type* #define S16PTRMAX(type, maxChars) type* #ifndef __GCENV_BASE_INCLUDED__ #define PTR_TO_TADDR(ptr) (reinterpret_cast<TADDR>(ptr)) #endif // __GCENV_BASE_INCLUDED__ #define GFN_TADDR(name) (reinterpret_cast<TADDR>(&(name))) #define GVAL_ADDR(g) (&(g)) #define _SPTR_DECL(acc_type, store_type, var) \ static store_type var #define _SPTR_IMPL(acc_type, store_type, cls, var) \ store_type cls::var #define _SPTR_IMPL_INIT(acc_type, store_type, cls, var, init) \ store_type cls::var = init #define _SPTR_IMPL_NS(acc_type, store_type, ns, cls, var) \ store_type cls::var #define _SPTR_IMPL_NS_INIT(acc_type, store_type, ns, cls, var, init) \ store_type cls::var = init #define _GPTR_DECL(acc_type, store_type, var) \ extern store_type var #define _GPTR_IMPL(acc_type, store_type, var) \ store_type var #define _GPTR_IMPL_INIT(acc_type, store_type, var, init) \ store_type var = init #define SVAL_DECL(type, var) \ static type var #define SVAL_IMPL(type, cls, var) \ type cls::var #define SVAL_IMPL_INIT(type, cls, var, init) \ type cls::var = init #define SVAL_IMPL_NS(type, ns, cls, var) \ type cls::var #define SVAL_IMPL_NS_INIT(type, ns, cls, var, init) \ type cls::var = init #define GVAL_DECL(type, var) \ extern type var #define GVAL_IMPL(type, var) \ type var #define GVAL_IMPL_INIT(type, var, init) \ type var = init #define GARY_DECL(type, var, size) \ extern type var[size] #define GARY_IMPL(type, var, size) \ type var[size] #define PTR_HOST_TO_TADDR(host) (reinterpret_cast<TADDR>(host)) #define PTR_HOST_INT_TO_TADDR(host) ((TADDR)(host)) #define VPTR_HOST_VTABLE_TO_TADDR(host) (reinterpret_cast<TADDR>(host)) #define PTR_HOST_MEMBER_TADDR(type, host, memb) (reinterpret_cast<TADDR>(&(host)->memb)) #define PTR_HOST_MEMBER(type, host, memb) (&((host)->memb)) #define PTR_HOST_INT_MEMBER_TADDR(type, host, memb) ((TADDR)&(host)->memb) #define PTR_TO_MEMBER_TADDR(type, ptr, memb) (reinterpret_cast<TADDR>(&((ptr)->memb))) #define PTR_TO_MEMBER(type, ptr, memb) (&((ptr)->memb)) #define PTR_READ(addr, size) (reinterpret_cast<void*>(addr)) #define PTR_NULL NULL #define DAC_EMPTY() #define DAC_EMPTY_ERR() #define DAC_EMPTY_RET(retVal) #define DAC_UNEXPECTED() #define DACCOP_IGNORE(warningCode, reasonString) #endif // !DACCESS_COMPILE //---------------------------------------------------------------------------- // dac_cast // Casting utility, to be used for casting one class pointer type to another. // Use as you would use static_cast // // dac_cast is designed to act just as static_cast does when // dealing with pointers and their DAC abstractions. Specifically, // it handles these coversions: // // dac_cast<TargetType>(SourceTypeVal) // // where TargetType <- SourceTypeVal are // // ?PTR(Tgt) <- TADDR - Create PTR type (DPtr etc.) from TADDR // ?PTR(Tgt) <- ?PTR(Src) - Convert one PTR type to another // ?PTR(Tgt) <- Src * - Create PTR type from dac host object instance // TADDR <- ?PTR(Src) - Get TADDR of PTR object (DPtr etc.) // TADDR <- Src * - Get TADDR of dac host object instance // // Note that there is no direct convertion to other host-pointer types (because we don't // know if you want a DPTR or VPTR etc.). However, due to the implicit DAC conversions, // you can just use dac_cast<PTR_Foo> and assign that to a Foo*. // // The beauty of this syntax is that it is consistent regardless // of source and target casting types. You just use dac_cast // and the partial template specialization will do the right thing. // // One important thing to realise is that all "Foo *" types are // assumed to be pointers to host instances that were marshalled by DAC. This should // fail at runtime if it's not the case. // // Some examples would be: // // - Host pointer of one type to a related host pointer of another // type, i.e., MethodDesc * <-> InstantiatedMethodDesc * // Syntax: with MethodDesc *pMD, InstantiatedMethodDesc *pInstMD // pInstMd = dac_cast<PTR_InstantiatedMethodDesc>(pMD) // pMD = dac_cast<PTR_MethodDesc>(pInstMD) // // - (D|V)PTR of one encapsulated pointer type to a (D|V)PTR of // another type, i.e., PTR_AppDomain <-> PTR_BaseDomain // Syntax: with PTR_AppDomain pAD, PTR_BaseDomain pBD // dac_cast<PTR_AppDomain>(pBD) // dac_cast<PTR_BaseDomain>(pAD) // // Example comparsions of some old and new syntax, where // h is a host pointer, such as "Foo *h;" // p is a DPTR, such as "PTR_Foo p;" // // PTR_HOST_TO_TADDR(h) ==> dac_cast<TADDR>(h) // PTR_TO_TADDR(p) ==> dac_cast<TADDR>(p) // PTR_Foo(PTR_HOST_TO_TADDR(h)) ==> dac_cast<PTR_Foo>(h) // //---------------------------------------------------------------------------- template <typename Tgt, typename Src> inline Tgt dac_cast(Src src) { #ifdef DACCESS_COMPILE // In DAC builds, first get a TADDR for the source, then create the // appropriate destination instance. TADDR addr = dac_imp::getTaddr(src); return dac_imp::makeDacInst<Tgt>::fromTaddr(addr); #else // !DACCESS_COMPILE // In non-DAC builds, dac_cast is the same as a C-style cast because we need to support: // - casting away const // - conversions between pointers and TADDR // Perhaps we should more precisely restrict it's usage, but we get the precise // restrictions in DAC builds, so it wouldn't buy us much. return (Tgt)(src); #endif // !DACCESS_COMPILE } //---------------------------------------------------------------------------- // // Convenience macros which work for either mode. // //---------------------------------------------------------------------------- #define SPTR_DECL(type, var) _SPTR_DECL(type*, PTR_##type, var) #define SPTR_IMPL(type, cls, var) _SPTR_IMPL(type*, PTR_##type, cls, var) #define SPTR_IMPL_INIT(type, cls, var, init) _SPTR_IMPL_INIT(type*, PTR_##type, cls, var, init) #define SPTR_IMPL_NS(type, ns, cls, var) _SPTR_IMPL_NS(type*, PTR_##type, ns, cls, var) #define SPTR_IMPL_NS_INIT(type, ns, cls, var, init) _SPTR_IMPL_NS_INIT(type*, PTR_##type, ns, cls, var, init) #define GPTR_DECL(type, var) _GPTR_DECL(type*, PTR_##type, var) #define GPTR_IMPL(type, var) _GPTR_IMPL(type*, PTR_##type, var) #define GPTR_IMPL_INIT(type, var, init) _GPTR_IMPL_INIT(type*, PTR_##type, var, init) // If you want to marshal a single instance of an ArrayDPtr over to the host and // return a pointer to it, you can use this function. However, this is unsafe because // users of value may assume they can do pointer arithmetic on it. This is exactly // the bugs ArrayDPtr is designed to prevent. See code:__ArrayDPtr for details. template<typename type> inline type* DacUnsafeMarshalSingleElement( ArrayDPTR(type) arrayPtr ) { return (DPTR(type))(arrayPtr); } typedef DPTR(int8_t) PTR_Int8; typedef DPTR(int16_t) PTR_Int16; typedef DPTR(int32_t) PTR_Int32; typedef DPTR(int64_t) PTR_Int64; typedef ArrayDPTR(uint8_t) PTR_UInt8; typedef DPTR(PTR_UInt8) PTR_PTR_UInt8; typedef DPTR(PTR_PTR_UInt8) PTR_PTR_PTR_UInt8; typedef DPTR(uint16_t) PTR_UInt16; typedef DPTR(uint32_t) PTR_UInt32; typedef DPTR(uint64_t) PTR_UInt64; typedef DPTR(uintptr_t) PTR_UIntNative; typedef DPTR(size_t) PTR_size_t; typedef uint8_t Code; typedef DPTR(Code) PTR_Code; typedef DPTR(PTR_Code) PTR_PTR_Code; #if defined(DACCESS_COMPILE) && defined(DAC_CLR_ENVIRONMENT) #include <corhdr.h> #include <clrdata.h> //#include <xclrdata.h> #endif // defined(DACCESS_COMPILE) && defined(DAC_CLR_ENVIRONMENT) //---------------------------------------------------------------------------- // PCODE is pointer to any executable code. typedef TADDR PCODE; typedef DPTR(TADDR) PTR_PCODE; //---------------------------------------------------------------------------- // // The access code compile must compile data structures that exactly // match the real structures for access to work. The access code // doesn't want all of the debugging validation code, though, so // distinguish between _DEBUG, for declaring general debugging data // and always-on debug code, and _DEBUG_IMPL, for debugging code // which will be disabled when compiling for external access. // //---------------------------------------------------------------------------- #if !defined(_DEBUG_IMPL) && defined(_DEBUG) && !defined(DACCESS_COMPILE) #define _DEBUG_IMPL 1 #endif // Helper macro for tracking EnumMemoryRegions progress. #if 0 #define EMEM_OUT(args) DacWarning args #else // !0 #define EMEM_OUT(args) #endif // !0 // TARGET_CONSISTENCY_CHECK represents a condition that should not fail unless the DAC target is corrupt. // This is in contrast to ASSERTs in DAC infrastructure code which shouldn't fail regardless of the memory // read from the target. At the moment we treat these the same, but in the future we will want a mechanism // for disabling just the target consistency checks (eg. for tests that intentionally use corrupted targets). // @dbgtodo rbyers: Separating asserts and target consistency checks is tracked by DevDiv Bugs 31674 #define TARGET_CONSISTENCY_CHECK(expr,msg) _ASSERTE_MSG(expr,msg) #ifdef DACCESS_COMPILE #define NO_DAC() static_assert(false, "Cannot use this method in builds DAC: " __FILE__ ":" __LINE__) #else #define NO_DAC() do {} while (0) #endif #endif // !__daccess_h__
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. //***************************************************************************** // File: daccess.h // // Support for external access of runtime data structures. These // macros and templates hide the details of pointer and data handling // so that data structures and code can be compiled to work both // in-process and through a special memory access layer. // // This code assumes the existence of two different pieces of code, // the target, the runtime code that is going to be examined, and // the host, the code that's doing the examining. Access to the // target is abstracted so the target may be a live process on the // same machine, a live process on a different machine, a dump file // or whatever. No assumptions should be made about accessibility // of the target. // // This code assumes that the data in the target is static. Any // time the target's data changes the interfaces must be reset so // that potentially stale data is discarded. // // This code is intended for read access and there is no // way to write data back currently. // // DAC-ized code: // - is read-only (non-invasive). So DACized codepaths can not trigger a GC. // - has no Thread* object. In reality, DAC-ized codepaths are // ReadProcessMemory calls from out-of-process. Conceptually, they // are like a pure-native (preemptive) thread. //// // This means that in particular, you cannot DACize a GCTRIGGERS function. // Neither can you DACize a function that throws if this will involve // allocating a new exception object. There may be // exceptions to these rules if you can guarantee that the DACized // part of the code path cannot cause a garbage collection (see // EditAndContinueModule::ResolveField for an example). // If you need to DACize a function that may trigger // a GC, it is probably best to refactor the function so that the DACized // part of the code path is in a separate function. For instance, // functions with GetOrCreate() semantics are hard to DAC-ize because // they the Create portion is inherently invasive. Instead, consider refactoring // into a GetOrFail() function that DAC can call; and then make GetOrCreate() // a wrapper around that. // // This code works by hiding the details of access to target memory. // Access is divided into two types: // 1. DPTR - access to a piece of data. // 2. VPTR - access to a class with a vtable. The class can only have // a single vtable pointer at the beginning of the class instance. // Things only need to be declared as VPTRs when it is necessary to // call virtual functions in the host. In that case the access layer // must do extra work to provide a host vtable for the object when // it is retrieved so that virtual functions can be called. // // When compiling with DACCESS_COMPILE the macros turn into templates // which replace pointers with smart pointers that know how to fetch // data from the target process and provide a host process version of it. // Normal data structure access will transparently receive a host copy // of the data and proceed, so code such as // typedef DPTR(Class) PTR_Class; // PTR_Class cls; // int val = cls->m_Int; // will work without modification. The appropriate operators are overloaded // to provide transparent access, such as the -> operator in this case. // Note that the convention is to create an appropriate typedef for // each type that will be accessed. This hides the particular details // of the type declaration and makes the usage look more like regular code. // // The ?PTR classes also have an implicit base type cast operator to // produce a host-pointer instance of the given type. For example // Class* cls = PTR_Class(addr); // works by implicit conversion from the PTR_Class created by wrapping // to a host-side Class instance. Again, this means that existing code // can work without modification. // // Code Example: // // typedef struct _rangesection // { // PTR_IJitManager pjit; // PTR_RangeSection pright; // PTR_RangeSection pleft; // ... Other fields omitted ... // } RangeSection; // // RangeSection* pRS = m_RangeTree; // // while (pRS != NULL) // { // if (currentPC < pRS->LowAddress) // pRS=pRS->pleft; // else if (currentPC > pRS->HighAddress) // pRS=pRS->pright; // else // { // return pRS->pjit; // } // } // // This code does not require any modifications. The global reference // provided by m_RangeTree will be a host version of the RangeSection // instantiated by conversion. The references to pRS->pleft and // pRS->pright will refer to DPTRs due to the modified declaration. // In the assignment statement the compiler will automatically use // the implicit conversion from PTR_RangeSection to RangeSection*, // causing a host instance to be created. Finally, if an appropriate // section is found the use of pRS->pjit will cause an implicit // conversion from PTR_IJitManager to IJitManager. The VPTR code // will look at target memory to determine the actual derived class // for the JitManager and instantiate the right class in the host so // that host virtual functions can be used just as they would in // the target. // // There are situations where code modifications are required, though. // // 1. Any time the actual value of an address matters, such as using // it as a search key in a tree, the target address must be used. // // An example of this is the RangeSection tree used to locate JIT // managers. A portion of this code is shown above. Each // RangeSection node in the tree describes a range of addresses // managed by the JitMan. These addresses are just being used as // values, not to dereference through, so there are not DPTRs. When // searching the range tree for an address the address used in the // search must be a target address as that's what values are kept in // the RangeSections. In the code shown above, currentPC must be a // target address as the RangeSections in the tree are all target // addresses. Use dac_cast<TADDR> to retrieve the target address // of a ?PTR, as well as to convert a host address to the // target address used to retrieve that particular instance. Do not // use dac_cast with any raw target pointer types (such as BYTE*). // // 2. Any time an address is modified, such as by address arithmetic, // the arithmetic must be performed on the target address. // // When a host instance is created it is created for the type in use. // There is no particular relation to any other instance, so address // arithmetic cannot be used to get from one instance to any other // part of memory. For example // char* Func(Class* cls) // { // // String follows the basic Class data. // return (char*)(cls + 1); // } // does not work with external access because the Class* used would // have retrieved only a Class worth of data. There is no string // following the host instance. Instead, this code should use // dac_cast<TADDR> to get the target address of the Class // instance, add sizeof(*cls) and then create a new ?PTR to access // the desired data. Note that the newly retrieved data will not // be contiguous with the Class instance, so address arithmetic // will still not work. // // Previous Code: // // BOOL IsTarget(LPVOID ip) // { // StubCallInstrs* pStubCallInstrs = GetStubCallInstrs(); // // if (ip == (LPVOID) &(pStubCallInstrs->m_op)) // { // return TRUE; // } // // Modified Code: // // BOOL IsTarget(LPVOID ip) // { // StubCallInstrs* pStubCallInstrs = GetStubCallInstrs(); // // if ((TADDR)ip == dac_cast<TADDR>(pStubCallInstrs) + // (TADDR)offsetof(StubCallInstrs, m_op)) // { // return TRUE; // } // // The parameter ip is a target address, so the host pStubCallInstrs // cannot be used to derive an address from. The member & reference // has to be replaced with a conversion from host to target address // followed by explicit offsetting for the field. // // PTR_HOST_MEMBER_TADDR is a convenience macro that encapsulates // these two operations, so the above code could also be: // // if ((TADDR)ip == // PTR_HOST_MEMBER_TADDR(StubCallInstrs, pStubCallInstrs, m_op)) // // 3. Any time the amount of memory referenced through an address // changes, such as by casting to a different type, a new ?PTR // must be created. // // Host instances are created and stored based on both the target // address and size of access. The access code has no way of knowing // all possible ways that data will be retrieved for a given address // so if code changes the way it accesses through an address a new // ?PTR must be used, which may lead to a difference instance and // different host address. This means that pointer identity does not hold // across casts, so code like // Class* cls = PTR_Class(addr); // Class2* cls2 = PTR_Class2(addr); // return cls == cls2; // will fail because the host-side instances have no relation to each // other. That isn't a problem, since by rule #1 you shouldn't be // relying on specific host address values. // // Previous Code: // // return (ArrayClass *) m_pMethTab->GetClass(); // // Modified Code: // // return PTR_ArrayClass(m_pMethTab->GetClass()); // // The ?PTR templates have an implicit conversion from a host pointer // to a target address, so the cast above constructs a new // PTR_ArrayClass by implicitly converting the host pointer result // from GetClass() to its target address and using that as the address // of the new PTR_ArrayClass. As mentioned, the actual host-side // pointer values may not be the same. // // Host pointer identity can be assumed as long as the type of access // is the same. In the example above, if both accesses were of type // Class then the host pointer will be the same, so it is safe to // retrieve the target address of an instance and then later get // a new host pointer for the target address using the same type as // the host pointer in that case will be the same. This is enabled // by caching all of the retrieved host instances. This cache is searched // by the addr:size pair and when there's a match the existing instance // is reused. This increases performance and also allows simple // pointer identity to hold. It does mean that host memory grows // in proportion to the amount of target memory being referenced, // so retrieving extraneous data should be avoided. // The host-side data cache grows until the Flush() method is called, // at which point all host-side data is discarded. No host // instance pointers should be held across a Flush(). // // Accessing into an object can lead to some unusual behavior. For // example, the SList class relies on objects to contain an SLink // instance that it uses for list maintenance. This SLink can be // embedded anywhere in the larger object. The SList access is always // purely to an SLink, so when using the access layer it will only // retrieve an SLink's worth of data. The SList template will then // do some address arithmetic to determine the start of the real // object and cast the resulting pointer to the final object type. // When using the access layer this results in a new ?PTR being // created and used, so a new instance will result. The internal // SLink instance will have no relation to the new object instance // even though in target address terms one is embedded in the other. // The assumption of data stability means that this won't cause // a problem, but care must be taken with the address arithmetic, // as layed out in rules #2 and #3. // // 4. Global address references cannot be used. Any reference to a // global piece of code or data, such as a function address, global // variable or class static variable, must be changed. // // The external access code may load at a different base address than // the target process code. Global addresses are therefore not // meaningful and must be replaced with something else. There isn't // a single solution, so replacements must be done on a case-by-case // basis. // // The simplest case is a global or class static variable. All // declarations must be replaced with a special declaration that // compiles into a modified accessor template value when compiled for // external data access. Uses of the variable automatically are fixed // up by the template instance. Note that assignment to the global // must be independently ifdef'ed as the external access layer should // not make any modifications. // // Macros allow for simple declaration of a class static and global // values that compile into an appropriate templated value. // // Previous Code: // // static RangeSection* m_RangeTree; // RangeSection* ExecutionManager::m_RangeTree; // // extern ThreadStore* g_pThreadStore; // ThreadStore* g_pThreadStore = &StaticStore; // class SystemDomain : public BaseDomain { // ... // ArrayListStatic m_appDomainIndexList; // ... // } // // SystemDomain::m_appDomainIndexList; // // extern DWORD gThreadTLSIndex; // // DWORD gThreadTLSIndex = TLS_OUT_OF_INDEXES; // // Modified Code: // // typedef DPTR(RangeSection) PTR_RangeSection; // SPTR_DECL(RangeSection, m_RangeTree); // SPTR_IMPL(RangeSection, ExecutionManager, m_RangeTree); // // typedef DPTR(ThreadStore) PTR_ThreadStore // GPTR_DECL(ThreadStore, g_pThreadStore); // GPTR_IMPL_INIT(ThreadStore, g_pThreadStore, &StaticStore); // // class SystemDomain : public BaseDomain { // ... // SVAL_DECL(ArrayListStatic; m_appDomainIndexList); // ... // } // // SVAL_IMPL(ArrayListStatic, SystemDomain, m_appDomainIndexList); // // GVAL_DECL(DWORD, gThreadTLSIndex); // // GVAL_IMPL_INIT(DWORD, gThreadTLSIndex, TLS_OUT_OF_INDEXES); // // When declaring the variable, the first argument declares the // variable's type and the second argument declares the variable's // name. When defining the variable the arguments are similar, with // an extra class name parameter for the static class variable case. // If an initializer is needed the IMPL_INIT macro should be used. // // Things get slightly more complicated when declaring an embedded // array. In this case the data element is not a single element and // therefore cannot be represented by a ?PTR. In the case of a global // array, you should use the GARY_DECL and GARY_IMPL macros. // We durrently have no support for declaring static array data members // or initialized arrays. Array data members that are dynamically allocated // need to be treated as pointer members. To reference individual elements // you must use pointer arithmetic (see rule 2 above). An array declared // as a local variable within a function does not need to be DACized. // // // All uses of ?VAL_DECL must have a corresponding entry given in the // DacGlobals structure in src\inc\dacvars.h. For SVAL_DECL the entry // is class__name. For GVAL_DECL the entry is dac__name. You must add // these entries in dacvars.h using the DEFINE_DACVAR macro. Note that // these entries also are used for dumping memory in mini dumps and // heap dumps. If it's not appropriate to dump a variable, (e.g., // it's an array or some other value that is not important to have // in a minidump) a second macro, DEFINE_DACVAR_NO_DUMP, will allow // you to make the required entry in the DacGlobals structure without // dumping its value. // // For convenience, here is a list of the various variable declaration and // initialization macros: // SVAL_DECL(type, name) static non-pointer data class MyClass // member declared within { // the class declaration // static int i; // SVAL_DECL(int, i); // } // // SVAL_IMPL(type, cls, name) static non-pointer data // int MyClass::i; // member defined outside SVAL_IMPL(int, MyClass, i); // the class declaration // // SVAL_IMPL_INIT(type, cls, static non-pointer data // int MyClass::i = 0; // name, val) member defined and SVAL_IMPL_INIT(int, MyClass, i, 0); // initialized outside the // class declaration // ------------------------------------------------------------------------------------------------ // SPTR_DECL(type, name) static pointer data class MyClass // member declared within { // the class declaration // static int * pInt; // SPTR_DECL(int, pInt); // } // // SPTR_IMPL(type, cls, name) static pointer data // int * MyClass::pInt; // member defined outside SPTR_IMPL(int, MyClass, pInt); // the class declaration // // SPTR_IMPL_INIT(type, cls, static pointer data // int * MyClass::pInt = NULL; // name, val) member defined and SPTR_IMPL_INIT(int, MyClass, pInt, NULL); // initialized outside the // class declaration // ------------------------------------------------------------------------------------------------ // GVAL_DECL(type, name) extern declaration of // extern int g_i // global non-pointer GVAL_DECL(int, g_i); // variable // // GVAL_IMPL(type, name) declaration of a // int g_i // global non-pointer GVAL_IMPL(int, g_i); // variable // // GVAL_IMPL_INIT (type, declaration and // int g_i = 0; // name, initialization of a GVAL_IMPL_INIT(int, g_i, 0); // val) global non-pointer // variable // ****Note**** // If you use GVAL_? to declare a global variable of a structured type and you need to // access a member of the type, you cannot use the dot operator. Instead, you must take the // address of the variable and use the arrow operator. For example: // struct // { // int x; // char ch; // } MyStruct; // GVAL_IMPL(MyStruct, g_myStruct); // int i = (&g_myStruct)->x; // ------------------------------------------------------------------------------------------------ // GPTR_DECL(type, name) extern declaration of // extern int * g_pInt // global pointer GPTR_DECL(int, g_pInt); // variable // // GPTR_IMPL(type, name) declaration of a // int * g_pInt // global pointer GPTR_IMPL(int, g_pInt); // variable // // GPTR_IMPL_INIT (type, declaration and // int * g_pInt = 0; // name, initialization of a GPTR_IMPL_INIT(int, g_pInt, NULL); // val) global pointer // variable // ------------------------------------------------------------------------------------------------ // GARY_DECL(type, name) extern declaration of // extern int g_rgIntList[MAX_ELEMENTS]; // a global array GPTR_DECL(int, g_rgIntList, MAX_ELEMENTS); // variable // // GARY_IMPL(type, name) declaration of a // int g_rgIntList[MAX_ELEMENTS]; // global pointer GPTR_IMPL(int, g_rgIntList, MAX_ELEMENTS); // variable // // // Certain pieces of code, such as the stack walker, rely on identifying // an object from its vtable address. As the target vtable addresses // do not necessarily correspond to the vtables used in the host, these // references must be translated. The access layer maintains translation // tables for all classes used with VPTR and can return the target // vtable pointer for any host vtable in the known list of VPTR classes. // // ----- Errors: // // All errors in the access layer are reported via exceptions. The // formal access layer methods catch all such exceptions and turn // them into the appropriate error, so this generally isn't visible // to users of the access layer. // // ----- DPTR Declaration: // // Create a typedef for the type with typedef DPTR(type) PTR_type; // Replace type* with PTR_type. // // ----- VPTR Declaration: // // VPTR can only be used on classes that have a single vtable // pointer at the beginning of the object. This should be true // for a normal single-inheritance object. // // All of the classes that may be instantiated need to be identified // and marked. In the base class declaration add either // VPTR_BASE_VTABLE_CLASS if the class is abstract or // VPTR_BASE_CONCRETE_VTABLE_CLASS if the class is concrete. In each // derived class add VPTR_VTABLE_CLASS. If you end up with compile or // link errors for an unresolved method called VPtrSize you missed a // derived class declaration. // // As described above, dac can only handle classes with a single // vtable. However, there's a special case for multiple inheritance // situations when only one of the classes is needed for dac. If // the base class needed is the first class in the derived class's // layout then it can be used with dac via using the VPTR_MULTI_CLASS // macros. Use with extreme care. // // All classes to be instantiated must be listed in src\inc\vptr_list.h. // // Create a typedef for the type with typedef VPTR(type) PTR_type; // When using a VPTR, replace Class* with PTR_Class. // // ----- Specific Macros: // // PTR_TO_TADDR(ptr) // Retrieves the raw target address for a ?PTR. // See code:dac_cast for the preferred alternative // // PTR_HOST_TO_TADDR(host) // Given a host address of an instance produced by a ?PTR reference, // return the original target address. The host address must // be an exact match for an instance. // See code:dac_cast for the preferred alternative // // PTR_HOST_INT_TO_TADDR(host) // Given a host address which resides somewhere within an instance // produced by a ?PTR reference (a host interior pointer) return the // corresponding target address. This is useful for evaluating // relative pointers (e.g. RelativePointer<T>) where calculating the // target address requires knowledge of the target address of the // relative pointer field itself. This lookup is slower than that for // a non-interior host pointer so use it sparingly. // // VPTR_HOST_VTABLE_TO_TADDR(host) // Given the host vtable pointer for a known VPTR class, return // the target vtable pointer. // // PTR_HOST_MEMBER_TADDR(type, host, memb) // Retrieves the target address of a host instance pointer and // offsets it by the given member's offset within the type. // // PTR_HOST_INT_MEMBER_TADDR(type, host, memb) // As above but will work for interior host pointers (see the // description of PTR_HOST_INT_TO_TADDR for an explanation of host // interior pointers). // // PTR_READ(addr, size) // Reads a block of memory from the target and returns a host // pointer for it. Useful for reading blocks of data from the target // whose size is only known at runtime, such as raw code for a jitted // method. If the data being read is actually an object, use SPTR // instead to get better type semantics. // // DAC_EMPTY() // DAC_EMPTY_ERR() // DAC_EMPTY_RET(retVal) // DAC_UNEXPECTED() // Provides an empty method implementation when compiled // for DACCESS_COMPILE. For example, use to stub out methods needed // for vtable entries but otherwise unused. // // These macros are designed to turn into normal code when compiled // without DACCESS_COMPILE. // //***************************************************************************** // See code:EEStartup#TableOfContents for EE overview #ifndef __daccess_h__ #define __daccess_h__ #ifndef __in #include <specstrings.h> #endif #define DACCESS_TABLE_RESOURCE L"COREXTERNALDATAACCESSRESOURCE" #include "type_traits.hpp" #ifdef DACCESS_COMPILE #include "safemath.h" #if defined(TARGET_AMD64) || defined(TARGET_ARM64) typedef uint64_t UIntTarget; #elif defined(TARGET_X86) typedef uint32_t UIntTarget; #elif defined(TARGET_ARM) typedef uint32_t UIntTarget; #else #error unexpected target architecture #endif // // This version of things wraps pointer access in // templates which understand how to retrieve data // through an access layer. In this case no assumptions // can be made that the current compilation processor or // pointer types match the target's processor or pointer types. // // Define TADDR as a non-pointer value so use of it as a pointer // will not work properly. Define it as unsigned so // pointer comparisons aren't affected by sign. // This requires special casting to ULONG64 to sign-extend if necessary. // XXX drewb - Cheating right now by not supporting cross-plat. typedef UIntTarget TADDR; // TSIZE_T used for counts or ranges that need to span the size of a // target pointer. For cross-plat, this may be different than SIZE_T // which reflects the host pointer size. typedef UIntTarget TSIZE_T; // Information stored in the DAC table of interest to the DAC implementation // Note that this information is shared between all instantiations of ClrDataAccess, so initialize // it just once in code:ClrDataAccess.GetDacGlobals (rather than use fields in ClrDataAccess); struct DacTableInfo { // On Windows, the first DWORD is the 32-bit timestamp read out of the runtime dll's debug directory. // The remaining 3 DWORDS must all be 0. // On Mac, this is the 16-byte UUID of the runtime dll. // It is used to validate that mscorwks is the same version as mscordacwks uint32_t dwID0; uint32_t dwID1; uint32_t dwID2; uint32_t dwID3; }; extern DacTableInfo g_dacTableInfo; // // The following table contains all the global information that data access needs to begin // operation. All of the values stored here are RVAs. DacGlobalBase() returns the current // base address to combine with to get a full target address. // typedef struct _DacGlobals { // These will define all of the dac related mscorwks static and global variables // TODO: update DacTableGen to parse "uint32_t" instead of "ULONG32" for the ids #ifdef DAC_CLR_ENVIRONMENT #define DEFINE_DACVAR(id_type, size, id) id_type id; #define DEFINE_DACVAR_NO_DUMP(id_type, size, id) id_type id; #else #define DEFINE_DACVAR(id_type, size, id) uint32_t id; #define DEFINE_DACVAR_NO_DUMP(id_type, size, id) uint32_t id; #endif #include "dacvars.h" #undef DEFINE_DACVAR_NO_DUMP #undef DEFINE_DACVAR /* // Global functions. ULONG fn__QueueUserWorkItemCallback; ULONG fn__ThreadpoolMgr__AsyncCallbackCompletion; ULONG fn__ThreadpoolMgr__AsyncTimerCallbackCompletion; ULONG fn__DACNotifyCompilationFinished; #ifdef HOST_X86 ULONG fn__NativeDelayFixupAsmStub; ULONG fn__NativeDelayFixupAsmStubRet; #endif // HOST_X86 ULONG fn__PInvokeCalliReturnFromCall; ULONG fn__NDirectGenericStubReturnFromCall; ULONG fn__DllImportForDelegateGenericStubReturnFromCall; */ } DacGlobals; extern DacGlobals g_dacGlobals; #ifdef __cplusplus extern "C" { #endif // These two functions are largely just for marking code // that is not fully converted. DacWarning prints a debug // message, while DacNotImpl throws a not-implemented exception. void __cdecl DacWarning(_In_ _In_z_ char* format, ...); void DacNotImpl(void); void DacError(HRESULT err); void __declspec(noreturn) DacError_NoRet(HRESULT err); TADDR DacGlobalBase(void); HRESULT DacReadAll(TADDR addr, void* buffer, uint32_t size, bool throwEx); #ifdef DAC_CLR_ENVIRONMENT HRESULT DacWriteAll(TADDR addr, PVOID buffer, ULONG32 size, bool throwEx); HRESULT DacAllocVirtual(TADDR addr, ULONG32 size, ULONG32 typeFlags, ULONG32 protectFlags, bool throwEx, TADDR* mem); HRESULT DacFreeVirtual(TADDR mem, ULONG32 size, ULONG32 typeFlags, bool throwEx); #endif // DAC_CLR_ENVIRONMENT /* We are simulating a tiny bit of memory existing in the debuggee address space that really isn't there. The memory appears to exist in the last 1KB of the memory space to make minimal risk that it collides with any legitimate debuggee memory. When the DAC uses DacInstantiateTypeByAddressHelper on these high addresses instead of getting back a pointer in the DAC_INSTANCE cache it will get back a pointer to specifically configured block of debugger memory. Rationale: This method was invented to solve a problem when doing stack walking in the DAC. When running in-process the register context has always been written to memory somewhere before the stackwalker begins to operate. The stackwalker doesn't track the registers themselves, but rather the storage locations where registers were written. When the DAC runs the registers haven't been saved anywhere - there is no memory address that refers to them. It would be easy to store the registers in the debugger's memory space but the Regdisplay is typed as PTR_UIntNative, not uintptr_t*. We could change REGDISPLAY to point at debugger local addresses, but then we would have the opposite problem, being unable to refer to stack addresses that are in the debuggee memory space. Options we could do: 1) Add discriminant bits to REGDISPLAY fields to record whether the pointer is local or remote a) Do it in the runtime definition - adds size and complexity to mrt100 for a debug only scenario b) Do it only in the DAC definition - breaks marshalling for types that are or contain REGDISPLAY (ie StackFrameIterator). 2) Add a new DebuggerREGDISPLAY type that can hold local or remote addresses, and then create parallel DAC stackwalking code that uses it. This is a bunch of work and has higher maintenance cost to keep both code paths operational and functionally identical. 3) Allocate space in debuggee that will be used to stash the registers when doing a debug stackwalk - increases runtime working set for debug only scenario and won't work for dumps 4) Same as #3, but don't actually allocate the space at runtime, just simulate that it was allocated within the debugger - risk of colliding with real runtime allocations, adds complexity to the DAC. #4 seems the best option to me, so we wound up here. */ // This address is picked to be very unlikely to collide with any real memory usage in the target #define SIMULATED_DEBUGGEE_MEMORY_BASE_ADDRESS ((TADDR) -1024) // The byte at ((TADDR)-1) isn't addressable at all, so we only have 1023 bytes of usable space // At the moment we only need 256 bytes at most. #define SIMULATED_DEBUGGEE_MEMORY_MAX_SIZE 1023 // Sets the simulated debuggee memory region, or clears it if pSimulatedDebuggeeMemory = NULL // See large comment above for more details. void SetSimulatedDebuggeeMemory(void* pSimulatedDebuggeeMemory, uint32_t cbSimulatedDebuggeeMemory); void* DacInstantiateTypeByAddress(TADDR addr, uint32_t size, bool throwEx); void* DacInstantiateTypeByAddressNoReport(TADDR addr, uint32_t size, bool throwEx); void* DacInstantiateClassByVTable(TADDR addr, uint32_t minSize, bool throwEx); // This method should not be used casually. Make sure simulatedTargetAddr does not cause collisions. See comment in dacfn.cpp for more details. void* DacInstantiateTypeAtSimulatedAddress(TADDR simulatedTargetAddr, uint32_t size, void* pLocalBuffer, bool throwEx); // Copy a null-terminated ascii or unicode string from the target to the host. // Note that most of the work here is to find the null terminator. If you know the exact length, // then you can also just call DacInstantiateTypebyAddress. char* DacInstantiateStringA(TADDR addr, uint32_t maxChars, bool throwEx); wchar_t* DacInstantiateStringW(TADDR addr, uint32_t maxChars, bool throwEx); TADDR DacGetTargetAddrForHostAddr(const void* ptr, bool throwEx); TADDR DacGetTargetAddrForHostInteriorAddr(const void* ptr, bool throwEx); TADDR DacGetTargetVtForHostVt(const void* vtHost, bool throwEx); wchar_t* DacGetVtNameW(TADDR targetVtable); // Report a region of memory to the debugger void DacEnumMemoryRegion(TADDR addr, TSIZE_T size, bool fExpectSuccess = true); HRESULT DacWriteHostInstance(void * host, bool throwEx); #ifdef DAC_CLR_ENVIRONMENT // Occasionally it's necessary to allocate some host memory for // instance data that's created on the fly and so doesn't directly // correspond to target memory. These are held and freed on flush // like other instances but can't be looked up by address. PVOID DacAllocHostOnlyInstance(ULONG32 size, bool throwEx); // Determines whether ASSERTs should be raised when inconsistencies in the target are detected bool DacTargetConsistencyAssertsEnabled(); // Host instances can be marked as they are enumerated in // order to break cycles. This function returns true if // the instance is already marked, otherwise it marks the // instance and returns false. bool DacHostPtrHasEnumMark(LPCVOID host); // Determines if EnumMemoryRegions has been called on a method descriptor. // This helps perf for minidumps of apps with large managed stacks. bool DacHasMethodDescBeenEnumerated(LPCVOID pMD); // Sets a flag indicating that EnumMemoryRegions on a method desciptor // has been successfully called. The function returns true if // this flag had been previously set. bool DacSetMethodDescEnumerated(LPCVOID pMD); // Determines if a method descriptor is valid BOOL DacValidateMD(LPCVOID pMD); // Enumerate the instructions around a call site to help debugger stack walking heuristics void DacEnumCodeForStackwalk(TADDR taCallEnd); // Given the address and the size of a memory range which is stored in the buffer, replace all the patches // in the buffer with the real opcodes. This is especially important on X64 where the unwinder needs to // disassemble the native instructions. class MemoryRange; HRESULT DacReplacePatchesInHostMemory(MemoryRange range, PVOID pBuffer); // // Convenience macros for EnumMemoryRegions implementations. // // Enumerate the given host instance and return // true if the instance hasn't already been enumerated. #define DacEnumHostDPtrMem(host) \ (!DacHostPtrHasEnumMark(host) ? \ (DacEnumMemoryRegion(PTR_HOST_TO_TADDR(host), sizeof(*host)), \ true) : false) #define DacEnumHostSPtrMem(host, type) \ (!DacHostPtrHasEnumMark(host) ? \ (DacEnumMemoryRegion(PTR_HOST_TO_TADDR(host), \ type::DacSize(PTR_HOST_TO_TADDR(host))), \ true) : false) #define DacEnumHostVPtrMem(host) \ (!DacHostPtrHasEnumMark(host) ? \ (DacEnumMemoryRegion(PTR_HOST_TO_TADDR(host), (host)->VPtrSize()), \ true) : false) // Check enumeration of 'this' and return if this has already been // enumerated. Making this the first line of an object's EnumMemoryRegions // method will prevent cycles. #define DAC_CHECK_ENUM_THIS() \ if (DacHostPtrHasEnumMark(this)) return #define DAC_ENUM_DTHIS() \ if (!DacEnumHostDPtrMem(this)) return #define DAC_ENUM_STHIS(type) \ if (!DacEnumHostSPtrMem(this, type)) return #define DAC_ENUM_VTHIS() \ if (!DacEnumHostVPtrMem(this)) return #endif // DAC_CLR_ENVIRONMENT #ifdef __cplusplus } // // Computes (taBase + (dwIndex * dwElementSize()), with overflow checks. // // Arguments: // taBase the base TADDR value // dwIndex the index of the offset // dwElementSize the size of each element (to multiply the offset by) // // Return value: // The resulting TADDR, or throws CORDB_E_TARGET_INCONSISTENT on overlow. // // Notes: // The idea here is that overflows during address arithmetic suggest that we're operating on corrupt // pointers. It helps to improve reliability to detect the cases we can (like overflow) and fail. Note // that this is just a heuristic, not a security measure. We can't trust target data regardless - // failing on overflow is just one easy case of corruption to detect. There is no need to use checked // arithmetic everywhere in the DAC infrastructure, this is intended just for the places most likely to // help catch bugs (eg. __DPtr::operator[]). // inline TADDR DacTAddrOffset( TADDR taBase, TSIZE_T dwIndex, TSIZE_T dwElementSize ) { #ifdef DAC_CLR_ENVIRONMENT ClrSafeInt<TADDR> t(taBase); t += ClrSafeInt<TSIZE_T>(dwIndex) * ClrSafeInt<TSIZE_T>(dwElementSize); if( t.IsOverflow() ) { // Pointer arithmetic overflow - probably due to corrupt target data //DacError(CORDBG_E_TARGET_INCONSISTENT); DacError(E_FAIL); } return t.Value(); #else // TODO: port safe math return taBase + (dwIndex*dwElementSize); #endif } // Base pointer wrapper which provides common behavior. class __TPtrBase { public: __TPtrBase() { // Make uninitialized pointers obvious. m_addr = (TADDR)-1; } explicit __TPtrBase(TADDR addr) { m_addr = addr; } bool operator!() const { return m_addr == 0; } // We'd like to have an implicit conversion to bool here since the C++ // standard says all pointer types are implicitly converted to bool. // Unfortunately, that would cause ambiguous overload errors for uses // of operator== and operator!=. Instead callers will have to compare // directly against NULL. bool operator==(TADDR addr) const { return m_addr == addr; } bool operator!=(TADDR addr) const { return m_addr != addr; } bool operator<(TADDR addr) const { return m_addr < addr; } bool operator>(TADDR addr) const { return m_addr > addr; } bool operator<=(TADDR addr) const { return m_addr <= addr; } bool operator>=(TADDR addr) const { return m_addr >= addr; } TADDR GetAddr(void) const { return m_addr; } TADDR SetAddr(TADDR addr) { m_addr = addr; return addr; } protected: TADDR m_addr; }; // Adds comparison operations // Its possible we just want to merge these into __TPtrBase, but SPtr isn't comparable with // other types right now and I would rather stay conservative class __ComparableTPtrBase : public __TPtrBase { protected: __ComparableTPtrBase(void) : __TPtrBase() {} explicit __ComparableTPtrBase(TADDR addr) : __TPtrBase(addr) {} public: bool operator==(const __ComparableTPtrBase& ptr) const { return m_addr == ptr.m_addr; } bool operator!=(const __ComparableTPtrBase& ptr) const { return !operator==(ptr); } bool operator<(const __ComparableTPtrBase& ptr) const { return m_addr < ptr.m_addr; } bool operator>(const __ComparableTPtrBase& ptr) const { return m_addr > ptr.m_addr; } bool operator<=(const __ComparableTPtrBase& ptr) const { return m_addr <= ptr.m_addr; } bool operator>=(const __ComparableTPtrBase& ptr) const { return m_addr >= ptr.m_addr; } }; // Pointer wrapper base class for various forms of normal data. // This has the common functionality between __DPtr and __ArrayDPtr. // The DPtrType type parameter is the actual derived type in use. This is necessary so that // inhereted functions preserve exact return types. template<typename type, typename DPtrType> class __DPtrBase : public __ComparableTPtrBase { public: typedef type _Type; typedef type* _Ptr; protected: // Constructors // All protected - this type should not be used directly - use one of the derived types instead. __DPtrBase< type, DPtrType >(void) : __ComparableTPtrBase() {} explicit __DPtrBase< type, DPtrType >(TADDR addr) : __ComparableTPtrBase(addr) {} explicit __DPtrBase(__TPtrBase addr) { m_addr = addr.GetAddr(); } explicit __DPtrBase(type const * host) { m_addr = DacGetTargetAddrForHostAddr(host, true); } public: DPtrType& operator=(const __TPtrBase& ptr) { m_addr = ptr.GetAddr(); return DPtrType(m_addr); } DPtrType& operator=(TADDR addr) { m_addr = addr; return DPtrType(m_addr); } type& operator*(void) const { return *(type*)DacInstantiateTypeByAddress(m_addr, sizeof(type), true); } using __ComparableTPtrBase::operator==; using __ComparableTPtrBase::operator!=; using __ComparableTPtrBase::operator<; using __ComparableTPtrBase::operator>; using __ComparableTPtrBase::operator<=; using __ComparableTPtrBase::operator>=; bool operator==(TADDR addr) const { return m_addr == addr; } bool operator!=(TADDR addr) const { return m_addr != addr; } // Array index operator // we want an operator[] for all possible numeric types (rather than rely on // implicit numeric conversions on the argument) to prevent ambiguity with // DPtr's implicit conversion to type* and the built-in operator[]. // @dbgtodo rbyers: we could also use this technique to simplify other operators below. template<typename indexType> type& operator[](indexType index) { // Compute the address of the element. TADDR elementAddr; if( index >= 0 ) { elementAddr = DacTAddrOffset(m_addr, index, sizeof(type)); } else { // Don't bother trying to do overflow checking for negative indexes - they are rare compared to // positive ones. ClrSafeInt doesn't support signed datatypes yet (although we should be able to add it // pretty easily). elementAddr = m_addr + index * sizeof(type); } // Marshal over a single instance and return a reference to it. return *(type*) DacInstantiateTypeByAddress(elementAddr, sizeof(type), true); } template<typename indexType> type const & operator[](indexType index) const { return (*const_cast<__DPtrBase*>(this))[index]; } //------------------------------------------------------------------------- // operator+ DPtrType operator+(unsigned short val) { return DPtrType(DacTAddrOffset(m_addr, val, sizeof(type))); } DPtrType operator+(short val) { return DPtrType(m_addr + val * sizeof(type)); } // size_t is unsigned int on Win32, so we need // to ifdef here to make sure the unsigned int // and size_t overloads don't collide. size_t // is marked __w64 so a simple unsigned int // will not work on Win32, it has to be size_t. DPtrType operator+(size_t val) { return DPtrType(DacTAddrOffset(m_addr, val, sizeof(type))); } #if (!defined (HOST_X86) && !defined(_SPARC_) && !defined(HOST_ARM)) || (defined(HOST_X86) && defined(__APPLE__)) DPtrType operator+(unsigned int val) { return DPtrType(DacTAddrOffset(m_addr, val, sizeof(type))); } #endif // (!defined (HOST_X86) && !defined(_SPARC_) && !defined(HOST_ARM)) || (defined(HOST_X86) && defined(__APPLE__)) DPtrType operator+(int val) { return DPtrType(m_addr + val * sizeof(type)); } #ifndef TARGET_UNIX // for now, everything else is 32 bit DPtrType operator+(unsigned long val) { return DPtrType(DacTAddrOffset(m_addr, val, sizeof(type))); } DPtrType operator+(long val) { return DPtrType(m_addr + val * sizeof(type)); } #endif // !TARGET_UNIX // for now, everything else is 32 bit #if !defined(HOST_ARM) && !defined(HOST_X86) DPtrType operator+(intptr_t val) { return DPtrType(m_addr + val * sizeof(type)); } #endif //------------------------------------------------------------------------- // operator- DPtrType operator-(unsigned short val) { return DPtrType(m_addr - val * sizeof(type)); } DPtrType operator-(short val) { return DPtrType(m_addr - val * sizeof(type)); } // size_t is unsigned int on Win32, so we need // to ifdef here to make sure the unsigned int // and size_t overloads don't collide. size_t // is marked __w64 so a simple unsigned int // will not work on Win32, it has to be size_t. DPtrType operator-(size_t val) { return DPtrType(m_addr - val * sizeof(type)); } DPtrType operator-(signed __int64 val) { return DPtrType(m_addr - val * sizeof(type)); } #if !defined (HOST_X86) && !defined(_SPARC_) && !defined(HOST_ARM) DPtrType operator-(unsigned int val) { return DPtrType(m_addr - val * sizeof(type)); } #endif // !defined (HOST_X86) && !defined(_SPARC_) && !defined(HOST_ARM) DPtrType operator-(int val) { return DPtrType(m_addr - val * sizeof(type)); } #ifdef _MSC_VER // for now, everything else is 32 bit DPtrType operator-(unsigned long val) { return DPtrType(m_addr - val * sizeof(type)); } DPtrType operator-(long val) { return DPtrType(m_addr - val * sizeof(type)); } #endif // _MSC_VER // for now, everything else is 32 bit size_t operator-(const DPtrType& val) { return (size_t)((m_addr - val.m_addr) / sizeof(type)); } //------------------------------------------------------------------------- DPtrType& operator+=(size_t val) { m_addr += val * sizeof(type); return static_cast<DPtrType&>(*this); } DPtrType& operator-=(size_t val) { m_addr -= val * sizeof(type); return static_cast<DPtrType&>(*this); } DPtrType& operator++() { m_addr += sizeof(type); return static_cast<DPtrType&>(*this); } DPtrType& operator--() { m_addr -= sizeof(type); return static_cast<DPtrType&>(*this); } DPtrType operator++(int postfix) { UNREFERENCED_PARAMETER(postfix); DPtrType orig = DPtrType(*this); m_addr += sizeof(type); return orig; } DPtrType operator--(int postfix) { UNREFERENCED_PARAMETER(postfix); DPtrType orig = DPtrType(*this); m_addr -= sizeof(type); return orig; } bool IsValid(void) const { return m_addr && DacInstantiateTypeByAddress(m_addr, sizeof(type), false) != NULL; } void EnumMem(void) const { DacEnumMemoryRegion(m_addr, sizeof(type)); } }; // Pointer wrapper for objects which are just plain data // and need no special handling. template<typename type> class __DPtr : public __DPtrBase<type,__DPtr<type> > { #ifdef __GNUC__ protected: //there seems to be a bug in GCC's inference logic. It can't find m_addr. using __DPtrBase<type,__DPtr<type> >::m_addr; #endif // __GNUC__ public: // constructors - all chain to __DPtrBase constructors __DPtr< type >(void) : __DPtrBase<type,__DPtr<type> >() {} __DPtr< type >(TADDR addr) : __DPtrBase<type,__DPtr<type> >(addr) {} // construct const from non-const typedef typename type_traits::remove_const<type>::type mutable_type; __DPtr< type >(__DPtr<mutable_type> const & rhs) : __DPtrBase<type,__DPtr<type> >(rhs.GetAddr()) {} explicit __DPtr< type >(__TPtrBase addr) : __DPtrBase<type,__DPtr<type> >(addr) {} explicit __DPtr< type >(type const * host) : __DPtrBase<type,__DPtr<type> >(host) {} operator type*() const { return (type*)DacInstantiateTypeByAddress(m_addr, sizeof(type), true); } type* operator->() const { return (type*)DacInstantiateTypeByAddress(m_addr, sizeof(type), true); } }; #define DPTR(type) __DPtr< type > // A restricted form of DPtr that doesn't have any conversions to pointer types. // This is useful for pointer types that almost always represent arrays, as opposed // to pointers to single instances (eg. PTR_BYTE). In these cases, allowing implicit // conversions to (for eg.) BYTE* would usually result in incorrect usage (eg. pointer // arithmetic and array indexing), since only a single instance has been marshalled to the host. // If you really must marshal a single instance (eg. converting T* to PTR_T is too painful for now), // then use code:DacUnsafeMarshalSingleElement so we can identify such unsafe code. template<typename type> class __ArrayDPtr : public __DPtrBase<type,__ArrayDPtr<type> > { public: // constructors - all chain to __DPtrBase constructors __ArrayDPtr< type >(void) : __DPtrBase<type,__ArrayDPtr<type> >() {} __ArrayDPtr< type >(TADDR addr) : __DPtrBase<type,__ArrayDPtr<type> >(addr) {} // construct const from non-const typedef typename type_traits::remove_const<type>::type mutable_type; __ArrayDPtr< type >(__ArrayDPtr<mutable_type> const & rhs) : __DPtrBase<type,__ArrayDPtr<type> >(rhs.GetAddr()) {} explicit __ArrayDPtr< type >(__TPtrBase addr) : __DPtrBase<type,__ArrayDPtr<type> >(addr) {} // Note that there is also no explicit constructor from host instances (type*). // Going this direction is less problematic, but often still represents risky coding. }; #define ArrayDPTR(type) __ArrayDPtr< type > // Pointer wrapper for objects which are just plain data // but whose size is not the same as the base type size. // This can be used for prefetching data for arrays or // for cases where an object has a variable size. template<typename type> class __SPtr : public __TPtrBase { public: typedef type _Type; typedef type* _Ptr; __SPtr< type >(void) : __TPtrBase() {} __SPtr< type >(TADDR addr) : __TPtrBase(addr) {} explicit __SPtr< type >(__TPtrBase addr) { m_addr = addr.GetAddr(); } explicit __SPtr< type >(type* host) { m_addr = DacGetTargetAddrForHostAddr(host, true); } __SPtr< type >& operator=(const __TPtrBase& ptr) { m_addr = ptr.m_addr; return *this; } __SPtr< type >& operator=(TADDR addr) { m_addr = addr; return *this; } operator type*() const { if (m_addr) { return (type*)DacInstantiateTypeByAddress(m_addr, type::DacSize(m_addr), true); } else { return (type*)NULL; } } type* operator->() const { if (m_addr) { return (type*)DacInstantiateTypeByAddress(m_addr, type::DacSize(m_addr), true); } else { return (type*)NULL; } } type& operator*(void) const { if (!m_addr) { DacError(E_INVALIDARG); } return *(type*)DacInstantiateTypeByAddress(m_addr, type::DacSize(m_addr), true); } bool IsValid(void) const { return m_addr && DacInstantiateTypeByAddress(m_addr, type::DacSize(m_addr), false) != NULL; } void EnumMem(void) const { if (m_addr) { DacEnumMemoryRegion(m_addr, type::DacSize(m_addr)); } } }; #define SPTR(type) __SPtr< type > // Pointer wrapper for objects which have a single leading // vtable, such as objects in a single-inheritance tree. // The base class of all such trees must have use // VPTR_BASE_VTABLE_CLASS in their declaration and all // instantiable members of the tree must be listed in vptr_list.h. template<class type> class __VPtr : public __TPtrBase { public: // VPtr::_Type has to be a pointer as // often the type is an abstract class. // This type is not expected to be used anyway. typedef type* _Type; typedef type* _Ptr; __VPtr< type >(void) : __TPtrBase() {} __VPtr< type >(TADDR addr) : __TPtrBase(addr) {} explicit __VPtr< type >(__TPtrBase addr) { m_addr = addr.GetAddr(); } explicit __VPtr< type >(type* host) { m_addr = DacGetTargetAddrForHostAddr(host, true); } __VPtr< type >& operator=(const __TPtrBase& ptr) { m_addr = ptr.m_addr; return *this; } __VPtr< type >& operator=(TADDR addr) { m_addr = addr; return *this; } operator type*() const { return (type*)DacInstantiateClassByVTable(m_addr, sizeof(type), true); } type* operator->() const { return (type*)DacInstantiateClassByVTable(m_addr, sizeof(type), true); } bool operator==(const __VPtr< type >& ptr) const { return m_addr == ptr.m_addr; } bool operator==(TADDR addr) const { return m_addr == addr; } bool operator!=(const __VPtr< type >& ptr) const { return !operator==(ptr); } bool operator!=(TADDR addr) const { return m_addr != addr; } bool IsValid(void) const { return m_addr && DacInstantiateClassByVTable(m_addr, sizeof(type), false) != NULL; } void EnumMem(void) const { if (IsValid()) { DacEnumMemoryRegion(m_addr, (operator->())->VPtrSize()); } } }; #define VPTR(type) __VPtr< type > // Pointer wrapper for 8-bit strings. #ifdef DAC_CLR_ENVIRONMENT template<typename type, ULONG32 maxChars = 32760> #else template<typename type, uint32_t maxChars = 32760> #endif class __Str8Ptr : public __DPtr<char> { public: typedef type _Type; typedef type* _Ptr; __Str8Ptr< type, maxChars >(void) : __DPtr<char>() {} __Str8Ptr< type, maxChars >(TADDR addr) : __DPtr<char>(addr) {} explicit __Str8Ptr< type, maxChars >(__TPtrBase addr) { m_addr = addr.GetAddr(); } explicit __Str8Ptr< type, maxChars >(type* host) { m_addr = DacGetTargetAddrForHostAddr(host, true); } __Str8Ptr< type, maxChars >& operator=(const __TPtrBase& ptr) { m_addr = ptr.m_addr; return *this; } __Str8Ptr< type, maxChars >& operator=(TADDR addr) { m_addr = addr; return *this; } operator type*() const { return (type*)DacInstantiateStringA(m_addr, maxChars, true); } bool IsValid(void) const { return m_addr && DacInstantiateStringA(m_addr, maxChars, false) != NULL; } void EnumMem(void) const { char* str = DacInstantiateStringA(m_addr, maxChars, false); if (str) { DacEnumMemoryRegion(m_addr, strlen(str) + 1); } } }; #define S8PTR(type) __Str8Ptr< type > #define S8PTRMAX(type, maxChars) __Str8Ptr< type, maxChars > // Pointer wrapper for 16-bit strings. #ifdef DAC_CLR_ENVIRONMENT template<typename type, ULONG32 maxChars = 32760> #else template<typename type, uint32_t maxChars = 32760> #endif class __Str16Ptr : public __DPtr<wchar_t> { public: typedef type _Type; typedef type* _Ptr; __Str16Ptr< type, maxChars >(void) : __DPtr<wchar_t>() {} __Str16Ptr< type, maxChars >(TADDR addr) : __DPtr<wchar_t>(addr) {} explicit __Str16Ptr< type, maxChars >(__TPtrBase addr) { m_addr = addr.GetAddr(); } explicit __Str16Ptr< type, maxChars >(type* host) { m_addr = DacGetTargetAddrForHostAddr(host, true); } __Str16Ptr< type, maxChars >& operator=(const __TPtrBase& ptr) { m_addr = ptr.m_addr; return *this; } __Str16Ptr< type, maxChars >& operator=(TADDR addr) { m_addr = addr; return *this; } operator type*() const { return (type*)DacInstantiateStringW(m_addr, maxChars, true); } bool IsValid(void) const { return m_addr && DacInstantiateStringW(m_addr, maxChars, false) != NULL; } void EnumMem(void) const { char* str = DacInstantiateStringW(m_addr, maxChars, false); if (str) { DacEnumMemoryRegion(m_addr, strlen(str) + 1); } } }; #define S16PTR(type) __Str16Ptr< type > #define S16PTRMAX(type, maxChars) __Str16Ptr< type, maxChars > template<typename type> class __GlobalVal { public: #ifdef DAC_CLR_ENVIRONMENT __GlobalVal< type >(PULONG rvaPtr) #else __GlobalVal< type >(uint32_t* rvaPtr) #endif { m_rvaPtr = rvaPtr; } operator type() const { return (type)*__DPtr< type >(DacGlobalBase() + *m_rvaPtr); } __DPtr< type > operator&() const { return __DPtr< type >(DacGlobalBase() + *m_rvaPtr); } // @dbgtodo rbyers dac support: This updates values in the host. This seems extremely dangerous // to do silently. I'd prefer that a specific (searchable) write function // was used. Try disabling this and see what fails... type & operator=(type & val) { type* ptr = __DPtr< type >(DacGlobalBase() + *m_rvaPtr); // Update the host copy; *ptr = val; // Write back to the target. DacWriteHostInstance(ptr, true); return val; } bool IsValid(void) const { return __DPtr< type >(DacGlobalBase() + *m_rvaPtr).IsValid(); } void EnumMem(void) const { TADDR p = DacGlobalBase() + *m_rvaPtr; __DPtr< type >(p).EnumMem(); } private: #ifdef DAC_CLR_ENVIRONMENT PULONG m_rvaPtr; #else uint32_t* m_rvaPtr; #endif }; template<typename type, size_t size> class __GlobalArray { public: #ifdef DAC_CLR_ENVIRONMENT __GlobalArray< type, size >(PULONG rvaPtr) #else __GlobalArray< type, size >(uint32_t* rvaPtr) #endif { m_rvaPtr = rvaPtr; } __DPtr< type > operator&() const { return __DPtr< type >(DacGlobalBase() + *m_rvaPtr); } type& operator[](unsigned int index) const { return __DPtr< type >(DacGlobalBase() + *m_rvaPtr)[index]; } bool IsValid(void) const { // Only validates the base pointer, not the full array range. return __DPtr< type >(DacGlobalBase() + *m_rvaPtr).IsValid(); } void EnumMem(void) const { DacEnumMemoryRegion(DacGlobalBase() + *m_rvaPtr, sizeof(type) * size); } private: #ifdef DAC_CLR_ENVIRONMENT PULONG m_rvaPtr; #else uint32_t* m_rvaPtr; #endif }; template<typename acc_type, typename store_type> class __GlobalPtr { public: #ifdef DAC_CLR_ENVIRONMENT __GlobalPtr< acc_type, store_type >(PULONG rvaPtr) #else __GlobalPtr< acc_type, store_type >(uint32_t* rvaPtr) #endif { m_rvaPtr = rvaPtr; } __DPtr< store_type > operator&() const { return __DPtr< store_type >(DacGlobalBase() + *m_rvaPtr); } store_type & operator=(store_type & val) { store_type* ptr = __DPtr< store_type >(DacGlobalBase() + *m_rvaPtr); // Update the host copy; *ptr = val; // Write back to the target. DacWriteHostInstance(ptr, true); return val; } acc_type operator->() const { return (acc_type)*__DPtr< store_type >(DacGlobalBase() + *m_rvaPtr); } operator acc_type() const { return (acc_type)*__DPtr< store_type >(DacGlobalBase() + *m_rvaPtr); } operator store_type() const { return *__DPtr< store_type >(DacGlobalBase() + *m_rvaPtr); } bool operator!() const { return !*__DPtr< store_type >(DacGlobalBase() + *m_rvaPtr); } typename store_type operator[](int index) const { return (*__DPtr< store_type >(DacGlobalBase() + *m_rvaPtr))[index]; } typename store_type operator[](unsigned int index) const { return (*__DPtr< store_type >(DacGlobalBase() + *m_rvaPtr))[index]; } TADDR GetAddr() const { return (*__DPtr< store_type >(DacGlobalBase() + *m_rvaPtr)).GetAddr(); } TADDR GetAddrRaw () const { return DacGlobalBase() + *m_rvaPtr; } // This is only testing the the pointer memory is available but does not verify // the memory that it points to. // bool IsValidPtr(void) const { return __DPtr< store_type >(DacGlobalBase() + *m_rvaPtr).IsValid(); } bool IsValid(void) const { return __DPtr< store_type >(DacGlobalBase() + *m_rvaPtr).IsValid() && (*__DPtr< store_type >(DacGlobalBase() + *m_rvaPtr)).IsValid(); } void EnumMem(void) const { __DPtr< store_type > ptr(DacGlobalBase() + *m_rvaPtr); ptr.EnumMem(); if (ptr.IsValid()) { (*ptr).EnumMem(); } } #ifdef DAC_CLR_ENVIRONMENT PULONG m_rvaPtr; #else uint32_t* m_rvaPtr; #endif }; template<typename acc_type, typename store_type> inline bool operator==(const __GlobalPtr<acc_type, store_type>& gptr, acc_type host) { return DacGetTargetAddrForHostAddr(host, true) == *__DPtr< TADDR >(DacGlobalBase() + *gptr.m_rvaPtr); } template<typename acc_type, typename store_type> inline bool operator!=(const __GlobalPtr<acc_type, store_type>& gptr, acc_type host) { return !operator==(gptr, host); } template<typename acc_type, typename store_type> inline bool operator==(acc_type host, const __GlobalPtr<acc_type, store_type>& gptr) { return DacGetTargetAddrForHostAddr(host, true) == *__DPtr< TADDR >(DacGlobalBase() + *gptr.m_rvaPtr); } template<typename acc_type, typename store_type> inline bool operator!=(acc_type host, const __GlobalPtr<acc_type, store_type>& gptr) { return !operator==(host, gptr); } // // __VoidPtr is a type that behaves like void* but for target pointers. // Behavior of PTR_VOID: // * has void* semantics. Will compile to void* in non-DAC builds (just like // other PTR types. Unlike TADDR, we want pointer semantics. // * NOT assignable from host pointer types or convertible to host pointer // types - ensures we can't confuse host and target pointers (we'll get // compiler errors if we try and cast between them). // * like void*, no pointer arithmetic or dereferencing is allowed // * like TADDR, can be used to construct any __DPtr / __VPtr instance // * representation is the same as a void* (for marshalling / casting) // // One way in which __VoidPtr is unlike void* is that it can't be cast to // pointer or integer types. On the one hand, this is a good thing as it forces // us to keep target pointers separate from other data types. On the other hand // in practice this means we have to use dac_cast<TADDR> in places where we used // to use a (TADDR) cast. Unfortunately C++ provides us no way to allow the // explicit cast to primitive types without also allowing implicit conversions. // // This is very similar in spirit to TADDR. The primary difference is that // PTR_VOID has pointer semantics, where TADDR has integer semantics. When // dacizing uses of void* to TADDR, casts must be inserted everywhere back to // pointer types. If we switch a use of TADDR to PTR_VOID, those casts in // DACCESS_COMPILE regions no longer compile (see above). Also, TADDR supports // pointer arithmetic, but that might not be necessary (could use PTR_BYTE // instead etc.). Ideally we'd probably have just one type for this purpose // (named TADDR but with the semantics of PTR_VOID), but outright conversion // would require too much work. // template <> class __DPtr<void> : public __ComparableTPtrBase { public: __DPtr(void) : __ComparableTPtrBase() {} __DPtr(TADDR addr) : __ComparableTPtrBase(addr) {} // Note, unlike __DPtr, this ctor form is not explicit. We allow implicit // conversions from any pointer type (just like for void*). __DPtr(__TPtrBase addr) { m_addr = addr.GetAddr(); } // Like TPtrBase, VoidPtrs can also be created impicitly from all GlobalPtrs template<typename acc_type, typename store_type> __DPtr(__GlobalPtr<acc_type, store_type> globalPtr) { m_addr = globalPtr.GetAddr(); } // Note, unlike __DPtr, there is no explicit conversion from host pointer // types. Since void* cannot be marshalled, there is no such thing as // a void* DAC instance in the host. // Also, we don't want an implicit conversion to TADDR because then the // compiler will allow pointer arithmetic (which it wouldn't allow for // void*). Instead, callers can use dac_cast<TADDR> if they want. // Note, unlike __DPtr, any pointer type can be assigned to a __DPtr // This is to mirror the assignability of any pointer type to a void* __DPtr& operator=(const __TPtrBase& ptr) { m_addr = ptr.GetAddr(); return *this; } __DPtr& operator=(TADDR addr) { m_addr = addr; return *this; } // note, no marshalling operators (type* conversion, operator ->, operator*) // A void* can't be marshalled because we don't know how much to copy // PTR_Void can be compared to any other pointer type (because conceptually, // any other pointer type should be implicitly convertible to void*) using __ComparableTPtrBase::operator==; using __ComparableTPtrBase::operator!=; using __ComparableTPtrBase::operator<; using __ComparableTPtrBase::operator>; using __ComparableTPtrBase::operator<=; using __ComparableTPtrBase::operator>=; bool operator==(TADDR addr) const { return m_addr == addr; } bool operator!=(TADDR addr) const { return m_addr != addr; } }; typedef __DPtr<void> __VoidPtr; typedef __VoidPtr PTR_VOID; typedef DPTR(PTR_VOID) PTR_PTR_VOID; // For now we treat pointers to const and non-const void the same in DAC // builds. In general, DAC is read-only anyway and so there isn't a danger of // writing to these pointers. Also, the non-dac builds will ensure // const-correctness. However, if we wanted to support true void* / const void* // behavior, we could probably build the follow functionality by templating // __VoidPtr: // * A PTR_VOID would be implicitly convertable to PTR_CVOID // * An explicit coercion (ideally const_cast) would be required to convert a // PTR_CVOID to a PTR_VOID // * Similarily, an explicit coercion would be required to convert a cost PTR // type (eg. PTR_CBYTE) to a PTR_VOID. typedef __VoidPtr PTR_CVOID; // The special empty ctor declared here allows the whole // class hierarchy to be instantiated easily by the // external access code. The actual class body will be // read externally so no members should be initialized. // Safe access for retrieving the target address of a PTR. #define PTR_TO_TADDR(ptr) ((ptr).GetAddr()) #define GFN_TADDR(name) (DacGlobalBase() + g_dacGlobals.fn__ ## name) // ROTORTODO - g++ 3 doesn't like the use of the operator& in __GlobalVal // here. Putting GVAL_ADDR in to get things to compile while I discuss // this matter with the g++ authors. #define GVAL_ADDR(g) \ ((g).operator&()) // // References to class static and global data. // These all need to be redirected through the global // data table. // #define _SPTR_DECL(acc_type, store_type, var) \ static __GlobalPtr< acc_type, store_type > var #define _SPTR_IMPL(acc_type, store_type, cls, var) \ __GlobalPtr< acc_type, store_type > cls::var(&g_dacGlobals.cls##__##var) #define _SPTR_IMPL_INIT(acc_type, store_type, cls, var, init) \ __GlobalPtr< acc_type, store_type > cls::var(&g_dacGlobals.cls##__##var) #define _SPTR_IMPL_NS(acc_type, store_type, ns, cls, var) \ __GlobalPtr< acc_type, store_type > cls::var(&g_dacGlobals.ns##__##cls##__##var) #define _SPTR_IMPL_NS_INIT(acc_type, store_type, ns, cls, var, init) \ __GlobalPtr< acc_type, store_type > cls::var(&g_dacGlobals.ns##__##cls##__##var) #define _GPTR_DECL(acc_type, store_type, var) \ extern __GlobalPtr< acc_type, store_type > var #define _GPTR_IMPL(acc_type, store_type, var) \ __GlobalPtr< acc_type, store_type > var(&g_dacGlobals.dac__##var) #define _GPTR_IMPL_INIT(acc_type, store_type, var, init) \ __GlobalPtr< acc_type, store_type > var(&g_dacGlobals.dac__##var) #define SVAL_DECL(type, var) \ static __GlobalVal< type > var #define SVAL_IMPL(type, cls, var) \ __GlobalVal< type > cls::var(&g_dacGlobals.cls##__##var) #define SVAL_IMPL_INIT(type, cls, var, init) \ __GlobalVal< type > cls::var(&g_dacGlobals.cls##__##var) #define SVAL_IMPL_NS(type, ns, cls, var) \ __GlobalVal< type > cls::var(&g_dacGlobals.ns##__##cls##__##var) #define SVAL_IMPL_NS_INIT(type, ns, cls, var, init) \ __GlobalVal< type > cls::var(&g_dacGlobals.ns##__##cls##__##var) #define GVAL_DECL(type, var) \ extern __GlobalVal< type > var #define GVAL_IMPL(type, var) \ __GlobalVal< type > var(&g_dacGlobals.dac__##var) #define GVAL_IMPL_INIT(type, var, init) \ __GlobalVal< type > var(&g_dacGlobals.dac__##var) #define GARY_DECL(type, var, size) \ extern __GlobalArray< type, size > var #define GARY_IMPL(type, var, size) \ __GlobalArray< type, size > var(&g_dacGlobals.dac__##var) // Translation from a host pointer back to the target address // that was used to retrieve the data for the host pointer. #define PTR_HOST_TO_TADDR(host) DacGetTargetAddrForHostAddr(host, true) // Translation from a host interior pointer back to the corresponding // target address. The host address must reside within a previously // retrieved instance. #define PTR_HOST_INT_TO_TADDR(host) DacGetTargetAddrForHostInteriorAddr(host, true) // Construct a pointer to a member of the given type. #define PTR_HOST_MEMBER_TADDR(type, host, memb) \ (PTR_HOST_TO_TADDR(host) + (TADDR)offsetof(type, memb)) // in the DAC build this is still typed TADDR, but in the runtime // build it preserves the member type. #define PTR_HOST_MEMBER(type, host, memb) \ (PTR_HOST_TO_TADDR(host) + (TADDR)offsetof(type, memb)) // Construct a pointer to a member of the given type given an interior // host address. #define PTR_HOST_INT_MEMBER_TADDR(type, host, memb) \ (PTR_HOST_INT_TO_TADDR(host) + (TADDR)offsetof(type, memb)) #define PTR_TO_MEMBER_TADDR(type, ptr, memb) \ (PTR_TO_TADDR(ptr) + (TADDR)offsetof(type, memb)) // in the DAC build this is still typed TADDR, but in the runtime // build it preserves the member type. #define PTR_TO_MEMBER(type, ptr, memb) \ (PTR_TO_TADDR(ptr) + (TADDR)offsetof(type, memb)) // Constructs an arbitrary data instance for a piece of // memory in the target. #define PTR_READ(addr, size) \ DacInstantiateTypeByAddress(addr, size, true) // This value is used to initialize target pointers to NULL. We want this to be TADDR type // (as opposed to, say, __TPtrBase) so that it can be used in the non-explicit ctor overloads, // eg. as an argument default value. // We can't always just use NULL because that's 0 which (in C++) can be any integer or pointer // type (causing an ambiguous overload compiler error when used in explicit ctor forms). #define PTR_NULL ((TADDR)0) // Provides an empty method implementation when compiled // for DACCESS_COMPILE. For example, use to stub out methods needed // for vtable entries but otherwise unused. // Note that these functions are explicitly NOT marked SUPPORTS_DAC so that we'll get a // DacCop warning if any calls to them are detected. // @dbgtodo rbyers: It's probably almost always wrong to call any such function, so // we should probably throw a better error (DacNotImpl), and ideally mark the function // DECLSPEC_NORETURN so we don't have to deal with fabricating return values and we can // get compiler warnings (unreachable code) anytime functions marked this way are called. #define DAC_EMPTY() { LEAF_CONTRACT; } #define DAC_EMPTY_ERR() { LEAF_CONTRACT; DacError(E_UNEXPECTED); } #define DAC_EMPTY_RET(retVal) { LEAF_CONTRACT; DacError(E_UNEXPECTED); return retVal; } #define DAC_UNEXPECTED() { LEAF_CONTRACT; DacError_NoRet(E_UNEXPECTED); } #endif // __cplusplus HRESULT DacGetTargetAddrForHostAddr(const void* ptr, TADDR * pTADDR); // Implementation details for dac_cast, should never be accessed directly. // See code:dac_cast for details and discussion. namespace dac_imp { //--------------------------------------------- // Conversion to TADDR // Forward declarations. template <typename> struct conversionHelper; template <typename T> TADDR getTaddr(T&& val); // Helper structs to get the target address of specific types // This non-specialized struct handles all instances of asTADDR that don't // take partially-specialized arguments. template <typename T> struct conversionHelper { inline static TADDR asTADDR(__TPtrBase const & tptr) { return PTR_TO_TADDR(tptr); } inline static TADDR asTADDR(TADDR addr) { return addr; } }; // Handles template <typename TypeT> struct conversionHelper<TypeT * &> { inline static TADDR asTADDR(TypeT * src) { TADDR addr = 0; if (DacGetTargetAddrForHostAddr(src, &addr) != S_OK) addr = DacGetTargetAddrForHostInteriorAddr(src, true); return addr; } }; template<typename acc_type, typename store_type> struct conversionHelper<__GlobalPtr<acc_type, store_type> const & > { inline static TADDR asTADDR(__GlobalPtr<acc_type, store_type> const & gptr) { return PTR_TO_TADDR(gptr); } }; // It is an error to try dac_cast on a __GlobalVal or a __GlobalArray. template<typename TypeT> struct conversionHelper< __GlobalVal<TypeT> const & > { inline static TADDR asTADDR(__GlobalVal<TypeT> const & gval) { static_assert(false, "Cannot use dac_cast on a __GlobalVal; first you must get its address using the '&' operator."); } }; template<typename TypeT, size_t size> struct conversionHelper< __GlobalArray<TypeT, size> const & > { inline static TADDR asTADDR(__GlobalArray<TypeT, size> const & garr) { static_assert(false, "Cannot use dac_cast on a __GlobalArray; first you must get its address using the '&' operator."); } }; // This is the main helper function, and it delegates to the above helper functions. // NOTE: this works because of C++0x reference collapsing rules for rvalue reference // arguments in template functions. template <typename T> TADDR getTaddr(T&& val) { return conversionHelper<T>::asTADDR(val); } //--------------------------------------------- // Conversion to DAC instance // Helper class to instantiate DAC instances from a TADDR // The default implementation assumes we want to create an instance of a PTR type template <typename T> struct makeDacInst { // First constructing a __TPtrBase and then constructing the target type // ensures that the target type can construct itself from a __TPtrBase. // This also prevents unknown user conversions from producing incorrect // results (since __TPtrBase can only be constructed from TADDR values). static inline T fromTaddr(TADDR addr) { return T(__TPtrBase(addr)); } }; // Specialization for creating TADDRs from TADDRs. template<> struct makeDacInst<TADDR> { static inline TADDR fromTaddr(TADDR addr) { return addr; } }; // Partial specialization for creating host instances. template <typename T> struct makeDacInst<T *> { static inline T * fromTaddr(TADDR addr) { return makeDacInst<DPTR(T)>::fromTaddr(addr); } }; /* struct Yes { char c[2]; }; struct No { char c; }; Yes& HasTPtrBase(__TPtrBase const *, ); No& HasTPtrBase(...); template <typename T> typename rh::std::enable_if< sizeof(HasTPtrBase(typename rh::std::remove_reference<T>::type *)) == sizeof(Yes), T>::type makeDacInst(TADDR addr) */ } // namespace dac_imp // DacCop in-line exclusion mechanism // Warnings - official home is DacCop\Shared\Warnings.cs, but we want a way for users to indicate // warning codes in a way that is descriptive to readers (not just code numbers). The names here // don't matter - DacCop just looks at the value enum DacCopWarningCode { // General Rules FieldAccess = 1, PointerArith = 2, PointerComparison = 3, InconsistentMarshalling = 4, CastBetweenAddressSpaces = 5, CastOfMarshalledType = 6, VirtualCallToNonVPtr = 7, UndacizedGlobalVariable = 8, // Function graph related CallUnknown = 701, CallNonDac = 702, CallVirtualUnknown = 704, CallVirtualNonDac = 705, }; // DACCOP_IGNORE is a mechanism to suppress DacCop violations from within the source-code. // See the DacCop wiki for guidance on how best to use this: http://mswikis/clr/dev/Pages/DacCop.aspx // // DACCOP_IGNORE will suppress a DacCop violation for the following (non-compound) statement. // For example: // // The "dual-mode DAC problem" occurs in a few places where a class is used both // // in the host, and marshalled from the target ... <further details> // DACCOP_IGNORE(CastBetweenAddressSpaces,"SBuffer has the dual-mode DAC problem"); // TADDR bufAddr = (TADDR)m_buffer; // // A call to DACCOP_IGNORE must occur as it's own statement, and can apply only to following // single-statements (not to compound statement blocks). Occasionally it is necessary to hoist // violation-inducing code out to its own statement (e.g., if it occurs in the conditional of an // if). // // Arguments: // code: a literal value from DacCopWarningCode indicating which violation should be suppressed. // szReasonString: a short description of why this exclusion is necessary. This is intended just // to help readers of the code understand the source of the problem, and what would be required // to fix it. More details can be provided in comments if desired. // inline void DACCOP_IGNORE(DacCopWarningCode code, const char * szReasonString) { UNREFERENCED_PARAMETER(code); UNREFERENCED_PARAMETER(szReasonString); // DacCop detects calls to this function. No implementation is necessary. } #else // !DACCESS_COMPILE // // This version of the macros turns into normal pointers // for unmodified in-proc compilation. // ******************************************************* // !!!!!!!!!!!!!!!!!!!!!!!!!NOTE!!!!!!!!!!!!!!!!!!!!!!!!!! // // Please search this file for the type name to find the // DAC versions of these definitions // // !!!!!!!!!!!!!!!!!!!!!!!!!NOTE!!!!!!!!!!!!!!!!!!!!!!!!!! // ******************************************************* // Declare TADDR as a non-pointer type so that arithmetic // can be done on it directly, as with the DACCESS_COMPILE definition. // This also helps expose pointer usage that may need to be changed. typedef uintptr_t TADDR; typedef void* PTR_VOID; typedef void** PTR_PTR_VOID; #define DPTR(type) type* #define ArrayDPTR(type) type* #define SPTR(type) type* #define VPTR(type) type* #define S8PTR(type) type* #define S8PTRMAX(type, maxChars) type* #define S16PTR(type) type* #define S16PTRMAX(type, maxChars) type* #ifndef __GCENV_BASE_INCLUDED__ #define PTR_TO_TADDR(ptr) (reinterpret_cast<TADDR>(ptr)) #endif // __GCENV_BASE_INCLUDED__ #define GFN_TADDR(name) (reinterpret_cast<TADDR>(&(name))) #define GVAL_ADDR(g) (&(g)) #define _SPTR_DECL(acc_type, store_type, var) \ static store_type var #define _SPTR_IMPL(acc_type, store_type, cls, var) \ store_type cls::var #define _SPTR_IMPL_INIT(acc_type, store_type, cls, var, init) \ store_type cls::var = init #define _SPTR_IMPL_NS(acc_type, store_type, ns, cls, var) \ store_type cls::var #define _SPTR_IMPL_NS_INIT(acc_type, store_type, ns, cls, var, init) \ store_type cls::var = init #define _GPTR_DECL(acc_type, store_type, var) \ extern store_type var #define _GPTR_IMPL(acc_type, store_type, var) \ store_type var #define _GPTR_IMPL_INIT(acc_type, store_type, var, init) \ store_type var = init #define SVAL_DECL(type, var) \ static type var #define SVAL_IMPL(type, cls, var) \ type cls::var #define SVAL_IMPL_INIT(type, cls, var, init) \ type cls::var = init #define SVAL_IMPL_NS(type, ns, cls, var) \ type cls::var #define SVAL_IMPL_NS_INIT(type, ns, cls, var, init) \ type cls::var = init #define GVAL_DECL(type, var) \ extern type var #define GVAL_IMPL(type, var) \ type var #define GVAL_IMPL_INIT(type, var, init) \ type var = init #define GARY_DECL(type, var, size) \ extern type var[size] #define GARY_IMPL(type, var, size) \ type var[size] #define PTR_HOST_TO_TADDR(host) (reinterpret_cast<TADDR>(host)) #define PTR_HOST_INT_TO_TADDR(host) ((TADDR)(host)) #define VPTR_HOST_VTABLE_TO_TADDR(host) (reinterpret_cast<TADDR>(host)) #define PTR_HOST_MEMBER_TADDR(type, host, memb) (reinterpret_cast<TADDR>(&(host)->memb)) #define PTR_HOST_MEMBER(type, host, memb) (&((host)->memb)) #define PTR_HOST_INT_MEMBER_TADDR(type, host, memb) ((TADDR)&(host)->memb) #define PTR_TO_MEMBER_TADDR(type, ptr, memb) (reinterpret_cast<TADDR>(&((ptr)->memb))) #define PTR_TO_MEMBER(type, ptr, memb) (&((ptr)->memb)) #define PTR_READ(addr, size) (reinterpret_cast<void*>(addr)) #define PTR_NULL NULL #define DAC_EMPTY() #define DAC_EMPTY_ERR() #define DAC_EMPTY_RET(retVal) #define DAC_UNEXPECTED() #define DACCOP_IGNORE(warningCode, reasonString) #endif // !DACCESS_COMPILE //---------------------------------------------------------------------------- // dac_cast // Casting utility, to be used for casting one class pointer type to another. // Use as you would use static_cast // // dac_cast is designed to act just as static_cast does when // dealing with pointers and their DAC abstractions. Specifically, // it handles these coversions: // // dac_cast<TargetType>(SourceTypeVal) // // where TargetType <- SourceTypeVal are // // ?PTR(Tgt) <- TADDR - Create PTR type (DPtr etc.) from TADDR // ?PTR(Tgt) <- ?PTR(Src) - Convert one PTR type to another // ?PTR(Tgt) <- Src * - Create PTR type from dac host object instance // TADDR <- ?PTR(Src) - Get TADDR of PTR object (DPtr etc.) // TADDR <- Src * - Get TADDR of dac host object instance // // Note that there is no direct convertion to other host-pointer types (because we don't // know if you want a DPTR or VPTR etc.). However, due to the implicit DAC conversions, // you can just use dac_cast<PTR_Foo> and assign that to a Foo*. // // The beauty of this syntax is that it is consistent regardless // of source and target casting types. You just use dac_cast // and the partial template specialization will do the right thing. // // One important thing to realise is that all "Foo *" types are // assumed to be pointers to host instances that were marshalled by DAC. This should // fail at runtime if it's not the case. // // Some examples would be: // // - Host pointer of one type to a related host pointer of another // type, i.e., MethodDesc * <-> InstantiatedMethodDesc * // Syntax: with MethodDesc *pMD, InstantiatedMethodDesc *pInstMD // pInstMd = dac_cast<PTR_InstantiatedMethodDesc>(pMD) // pMD = dac_cast<PTR_MethodDesc>(pInstMD) // // - (D|V)PTR of one encapsulated pointer type to a (D|V)PTR of // another type, i.e., PTR_AppDomain <-> PTR_BaseDomain // Syntax: with PTR_AppDomain pAD, PTR_BaseDomain pBD // dac_cast<PTR_AppDomain>(pBD) // dac_cast<PTR_BaseDomain>(pAD) // // Example comparsions of some old and new syntax, where // h is a host pointer, such as "Foo *h;" // p is a DPTR, such as "PTR_Foo p;" // // PTR_HOST_TO_TADDR(h) ==> dac_cast<TADDR>(h) // PTR_TO_TADDR(p) ==> dac_cast<TADDR>(p) // PTR_Foo(PTR_HOST_TO_TADDR(h)) ==> dac_cast<PTR_Foo>(h) // //---------------------------------------------------------------------------- template <typename Tgt, typename Src> inline Tgt dac_cast(Src src) { #ifdef DACCESS_COMPILE // In DAC builds, first get a TADDR for the source, then create the // appropriate destination instance. TADDR addr = dac_imp::getTaddr(src); return dac_imp::makeDacInst<Tgt>::fromTaddr(addr); #else // !DACCESS_COMPILE // In non-DAC builds, dac_cast is the same as a C-style cast because we need to support: // - casting away const // - conversions between pointers and TADDR // Perhaps we should more precisely restrict it's usage, but we get the precise // restrictions in DAC builds, so it wouldn't buy us much. return (Tgt)(src); #endif // !DACCESS_COMPILE } //---------------------------------------------------------------------------- // // Convenience macros which work for either mode. // //---------------------------------------------------------------------------- #define SPTR_DECL(type, var) _SPTR_DECL(type*, PTR_##type, var) #define SPTR_IMPL(type, cls, var) _SPTR_IMPL(type*, PTR_##type, cls, var) #define SPTR_IMPL_INIT(type, cls, var, init) _SPTR_IMPL_INIT(type*, PTR_##type, cls, var, init) #define SPTR_IMPL_NS(type, ns, cls, var) _SPTR_IMPL_NS(type*, PTR_##type, ns, cls, var) #define SPTR_IMPL_NS_INIT(type, ns, cls, var, init) _SPTR_IMPL_NS_INIT(type*, PTR_##type, ns, cls, var, init) #define GPTR_DECL(type, var) _GPTR_DECL(type*, PTR_##type, var) #define GPTR_IMPL(type, var) _GPTR_IMPL(type*, PTR_##type, var) #define GPTR_IMPL_INIT(type, var, init) _GPTR_IMPL_INIT(type*, PTR_##type, var, init) // If you want to marshal a single instance of an ArrayDPtr over to the host and // return a pointer to it, you can use this function. However, this is unsafe because // users of value may assume they can do pointer arithmetic on it. This is exactly // the bugs ArrayDPtr is designed to prevent. See code:__ArrayDPtr for details. template<typename type> inline type* DacUnsafeMarshalSingleElement( ArrayDPTR(type) arrayPtr ) { return (DPTR(type))(arrayPtr); } typedef DPTR(int8_t) PTR_Int8; typedef DPTR(int16_t) PTR_Int16; typedef DPTR(int32_t) PTR_Int32; typedef DPTR(int64_t) PTR_Int64; typedef ArrayDPTR(uint8_t) PTR_UInt8; typedef DPTR(PTR_UInt8) PTR_PTR_UInt8; typedef DPTR(PTR_PTR_UInt8) PTR_PTR_PTR_UInt8; typedef DPTR(uint16_t) PTR_UInt16; typedef DPTR(uint32_t) PTR_UInt32; typedef DPTR(uint64_t) PTR_UInt64; typedef DPTR(uintptr_t) PTR_UIntNative; typedef DPTR(size_t) PTR_size_t; typedef uint8_t Code; typedef DPTR(Code) PTR_Code; typedef DPTR(PTR_Code) PTR_PTR_Code; #if defined(DACCESS_COMPILE) && defined(DAC_CLR_ENVIRONMENT) #include <corhdr.h> #include <clrdata.h> //#include <xclrdata.h> #endif // defined(DACCESS_COMPILE) && defined(DAC_CLR_ENVIRONMENT) //---------------------------------------------------------------------------- // PCODE is pointer to any executable code. typedef TADDR PCODE; typedef DPTR(TADDR) PTR_PCODE; //---------------------------------------------------------------------------- // // The access code compile must compile data structures that exactly // match the real structures for access to work. The access code // doesn't want all of the debugging validation code, though, so // distinguish between _DEBUG, for declaring general debugging data // and always-on debug code, and _DEBUG_IMPL, for debugging code // which will be disabled when compiling for external access. // //---------------------------------------------------------------------------- #if !defined(_DEBUG_IMPL) && defined(_DEBUG) && !defined(DACCESS_COMPILE) #define _DEBUG_IMPL 1 #endif // Helper macro for tracking EnumMemoryRegions progress. #if 0 #define EMEM_OUT(args) DacWarning args #else // !0 #define EMEM_OUT(args) #endif // !0 // TARGET_CONSISTENCY_CHECK represents a condition that should not fail unless the DAC target is corrupt. // This is in contrast to ASSERTs in DAC infrastructure code which shouldn't fail regardless of the memory // read from the target. At the moment we treat these the same, but in the future we will want a mechanism // for disabling just the target consistency checks (eg. for tests that intentionally use corrupted targets). // @dbgtodo rbyers: Separating asserts and target consistency checks is tracked by DevDiv Bugs 31674 #define TARGET_CONSISTENCY_CHECK(expr,msg) _ASSERTE_MSG(expr,msg) #ifdef DACCESS_COMPILE #define NO_DAC() static_assert(false, "Cannot use this method in builds DAC: " __FILE__ ":" __LINE__) #else #define NO_DAC() do {} while (0) #endif #endif // !__daccess_h__
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/native/external/brotli/common/context.c
#include "./context.h" #include <brotli/types.h> /* Common context lookup table for all context modes. */ const uint8_t _kBrotliContextLookupTable[2048] = { /* CONTEXT_LSB6, last byte. */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* CONTEXT_LSB6, second last byte, */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* CONTEXT_MSB6, last byte. */ 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 24, 25, 25, 25, 25, 26, 26, 26, 26, 27, 27, 27, 27, 28, 28, 28, 28, 29, 29, 29, 29, 30, 30, 30, 30, 31, 31, 31, 31, 32, 32, 32, 32, 33, 33, 33, 33, 34, 34, 34, 34, 35, 35, 35, 35, 36, 36, 36, 36, 37, 37, 37, 37, 38, 38, 38, 38, 39, 39, 39, 39, 40, 40, 40, 40, 41, 41, 41, 41, 42, 42, 42, 42, 43, 43, 43, 43, 44, 44, 44, 44, 45, 45, 45, 45, 46, 46, 46, 46, 47, 47, 47, 47, 48, 48, 48, 48, 49, 49, 49, 49, 50, 50, 50, 50, 51, 51, 51, 51, 52, 52, 52, 52, 53, 53, 53, 53, 54, 54, 54, 54, 55, 55, 55, 55, 56, 56, 56, 56, 57, 57, 57, 57, 58, 58, 58, 58, 59, 59, 59, 59, 60, 60, 60, 60, 61, 61, 61, 61, 62, 62, 62, 62, 63, 63, 63, 63, /* CONTEXT_MSB6, second last byte, */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* CONTEXT_UTF8, last byte. */ /* ASCII range. */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 12, 16, 12, 12, 20, 12, 16, 24, 28, 12, 12, 32, 12, 36, 12, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 32, 32, 24, 40, 28, 12, 12, 48, 52, 52, 52, 48, 52, 52, 52, 48, 52, 52, 52, 52, 52, 48, 52, 52, 52, 52, 52, 48, 52, 52, 52, 52, 52, 24, 12, 28, 12, 12, 12, 56, 60, 60, 60, 56, 60, 60, 60, 56, 60, 60, 60, 60, 60, 56, 60, 60, 60, 60, 60, 56, 60, 60, 60, 60, 60, 24, 12, 28, 12, 0, /* UTF8 continuation byte range. */ 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, /* UTF8 lead byte range. */ 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, /* CONTEXT_UTF8 second last byte. */ /* ASCII range. */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 0, /* UTF8 continuation byte range. */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* UTF8 lead byte range. */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* CONTEXT_SIGNED, last byte, same as the above values shifted by 3 bits. */ 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 56, /* CONTEXT_SIGNED, second last byte. */ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, };
#include "./context.h" #include <brotli/types.h> /* Common context lookup table for all context modes. */ const uint8_t _kBrotliContextLookupTable[2048] = { /* CONTEXT_LSB6, last byte. */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* CONTEXT_LSB6, second last byte, */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* CONTEXT_MSB6, last byte. */ 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 24, 25, 25, 25, 25, 26, 26, 26, 26, 27, 27, 27, 27, 28, 28, 28, 28, 29, 29, 29, 29, 30, 30, 30, 30, 31, 31, 31, 31, 32, 32, 32, 32, 33, 33, 33, 33, 34, 34, 34, 34, 35, 35, 35, 35, 36, 36, 36, 36, 37, 37, 37, 37, 38, 38, 38, 38, 39, 39, 39, 39, 40, 40, 40, 40, 41, 41, 41, 41, 42, 42, 42, 42, 43, 43, 43, 43, 44, 44, 44, 44, 45, 45, 45, 45, 46, 46, 46, 46, 47, 47, 47, 47, 48, 48, 48, 48, 49, 49, 49, 49, 50, 50, 50, 50, 51, 51, 51, 51, 52, 52, 52, 52, 53, 53, 53, 53, 54, 54, 54, 54, 55, 55, 55, 55, 56, 56, 56, 56, 57, 57, 57, 57, 58, 58, 58, 58, 59, 59, 59, 59, 60, 60, 60, 60, 61, 61, 61, 61, 62, 62, 62, 62, 63, 63, 63, 63, /* CONTEXT_MSB6, second last byte, */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* CONTEXT_UTF8, last byte. */ /* ASCII range. */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 12, 16, 12, 12, 20, 12, 16, 24, 28, 12, 12, 32, 12, 36, 12, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 32, 32, 24, 40, 28, 12, 12, 48, 52, 52, 52, 48, 52, 52, 52, 48, 52, 52, 52, 52, 52, 48, 52, 52, 52, 52, 52, 48, 52, 52, 52, 52, 52, 24, 12, 28, 12, 12, 12, 56, 60, 60, 60, 56, 60, 60, 60, 56, 60, 60, 60, 60, 60, 56, 60, 60, 60, 60, 60, 56, 60, 60, 60, 60, 60, 24, 12, 28, 12, 0, /* UTF8 continuation byte range. */ 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, /* UTF8 lead byte range. */ 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, /* CONTEXT_UTF8 second last byte. */ /* ASCII range. */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 0, /* UTF8 continuation byte range. */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* UTF8 lead byte range. */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* CONTEXT_SIGNED, last byte, same as the above values shifted by 3 bits. */ 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 56, /* CONTEXT_SIGNED, second last byte. */ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, };
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/mono/mono/metadata/w32error-win32.c
/** * \file */ #include <windows.h> #include "w32error.h" guint32 mono_w32error_get_last (void) { return GetLastError (); } void mono_w32error_set_last (guint32 error) { SetLastError (error); } guint32 mono_w32error_unix_to_win32 (guint32 error) { g_assert_not_reached (); }
/** * \file */ #include <windows.h> #include "w32error.h" guint32 mono_w32error_get_last (void) { return GetLastError (); } void mono_w32error_set_last (guint32 error) { SetLastError (error); } guint32 mono_w32error_unix_to_win32 (guint32 error) { g_assert_not_reached (); }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/inc/allocacheck.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*********************************************************************/ /* AllocaCheck */ /*********************************************************************/ /* check for alloca overruns (which otherwise are hard to track down and often only repro on optimized builds). USAGE: void foo() { ALLOCA_CHECK(); // Declare at function level scope .... void* mem = ALLOCA(size); // does an alloca, } // destructor of ALLOCA_CHECK for buffer overruns. */ /* */ /*********************************************************************/ #ifndef AllocaCheck_h #define AllocaCheck_h #include <malloc.h> // for alloca itself #if defined(assert) && !defined(_ASSERTE) #define _ASSERTE assert #endif #if defined(_DEBUG) || defined(DEBUG) /*********************************************************************/ class AllocaCheck { public: enum { CheckBytes = 0xCCCDCECF, }; struct AllocaSentinal { int check; AllocaSentinal* next; }; public: /***************************************************/ AllocaCheck() { sentinals = 0; } ~AllocaCheck() { AllocaSentinal* ptr = sentinals; while (ptr != 0) { if (ptr->check != (int)CheckBytes) _ASSERTE(!"alloca buffer overrun"); ptr = ptr->next; } } void* add(void* allocaBuff, unsigned size) { AllocaSentinal* newSentinal = (AllocaSentinal*) ((char*) allocaBuff + size); newSentinal->check = CheckBytes; newSentinal->next = sentinals; sentinals = newSentinal; memset(allocaBuff, 0xDD, size); return allocaBuff; } private: AllocaSentinal* sentinals; }; #define ALLOCA_CHECK() AllocaCheck __allocaChecker #define ALLOCA(size) __allocaChecker.add(_alloca(size+sizeof(AllocaCheck::AllocaSentinal)), size); #else #define ALLOCA_CHECK() #define ALLOCA(size) _alloca(size) #endif #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*********************************************************************/ /* AllocaCheck */ /*********************************************************************/ /* check for alloca overruns (which otherwise are hard to track down and often only repro on optimized builds). USAGE: void foo() { ALLOCA_CHECK(); // Declare at function level scope .... void* mem = ALLOCA(size); // does an alloca, } // destructor of ALLOCA_CHECK for buffer overruns. */ /* */ /*********************************************************************/ #ifndef AllocaCheck_h #define AllocaCheck_h #include <malloc.h> // for alloca itself #if defined(assert) && !defined(_ASSERTE) #define _ASSERTE assert #endif #if defined(_DEBUG) || defined(DEBUG) /*********************************************************************/ class AllocaCheck { public: enum { CheckBytes = 0xCCCDCECF, }; struct AllocaSentinal { int check; AllocaSentinal* next; }; public: /***************************************************/ AllocaCheck() { sentinals = 0; } ~AllocaCheck() { AllocaSentinal* ptr = sentinals; while (ptr != 0) { if (ptr->check != (int)CheckBytes) _ASSERTE(!"alloca buffer overrun"); ptr = ptr->next; } } void* add(void* allocaBuff, unsigned size) { AllocaSentinal* newSentinal = (AllocaSentinal*) ((char*) allocaBuff + size); newSentinal->check = CheckBytes; newSentinal->next = sentinals; sentinals = newSentinal; memset(allocaBuff, 0xDD, size); return allocaBuff; } private: AllocaSentinal* sentinals; }; #define ALLOCA_CHECK() AllocaCheck __allocaChecker #define ALLOCA(size) __allocaChecker.add(_alloca(size+sizeof(AllocaCheck::AllocaSentinal)), size); #else #define ALLOCA_CHECK() #define ALLOCA(size) _alloca(size) #endif #endif
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/tests/Interop/PInvoke/Primitives/Pointer/CMakeLists.txt
include ("${CLR_INTEROP_TEST_ROOT}/Interop.cmake") set(SOURCES NonBlittablePointerNative.cpp ) add_library (NonBlittablePointerNative SHARED ${SOURCES}) install (TARGETS NonBlittablePointerNative DESTINATION bin)
include ("${CLR_INTEROP_TEST_ROOT}/Interop.cmake") set(SOURCES NonBlittablePointerNative.cpp ) add_library (NonBlittablePointerNative SHARED ${SOURCES}) install (TARGETS NonBlittablePointerNative DESTINATION bin)
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/hosts/coreshim/CoreShim.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #ifndef _CORESHIM_H_ #define _CORESHIM_H_ // Platform #define NOMINMAX #include <Windows.h> #include <combaseapi.h> // Standard library #include <utility> #include <string> #include <cstdint> #include <cassert> // CoreCLR #include <palclr.h> #include <coreclrhost.h> #include <minipal/utils.h> #define WCHAR wchar_t #define RETURN_IF_FAILED(exp) { hr = (exp); if (FAILED(hr)) { assert(false && #exp); return hr; } } template < typename T, T DEFAULT, void(*RELEASE)(T) > struct AutoClass { T c; AutoClass() : c{ DEFAULT } { } AutoClass(_Inout_ T t) : c{ t } { } AutoClass(_In_ const AutoClass&) = delete; AutoClass& operator=(_In_ const AutoClass&) = delete; AutoClass(_Inout_ AutoClass &&other) : c{ other.Detach() } { } AutoClass& operator=(_Inout_ AutoClass &&other) { Attach(other.Detach()); } ~AutoClass() { Attach(DEFAULT); } operator T() { return c; } T* operator &() { return &c; } void Attach(_In_opt_ T cm) { RELEASE(c); c = cm; } T Detach() { T tmp = c; c = DEFAULT; return tmp; } }; inline void ReleaseHandle(_In_ HANDLE h) { if (h != nullptr && h != INVALID_HANDLE_VALUE) ::CloseHandle(h); } using AutoHandle = AutoClass<HANDLE, nullptr, &ReleaseHandle>; inline void ReleaseFindFile(_In_ HANDLE h) { if (h != nullptr) ::FindClose(h); } using AutoFindFile = AutoClass<HANDLE, nullptr, &ReleaseFindFile>; inline void ReleaseModule(_In_ HMODULE m) { if (m != nullptr) ::FreeLibrary(m); } using AutoModule = AutoClass<HMODULE, nullptr, &ReleaseModule>; namespace Utility { /// <summary> /// Get the supplied environment variable. /// </summary> HRESULT TryGetEnvVar(_In_z_ const WCHAR *env, _Inout_ std::wstring &envVar); /// <summary> /// Get the CoreShim directory. /// </summary> HRESULT GetCoreShimDirectory(_Inout_ std::string &dir); HRESULT GetCoreShimDirectory(_Inout_ std::wstring &dir); } // CoreShim environment variables used to indicate what assembly/type tuple // to load during COM activation. #define COMACT_ASSEMBLYNAME_ENVVAR W("CORESHIM_COMACT_ASSEMBLYNAME") #define COMACT_TYPENAME_ENVVAR W("CORESHIM_COMACT_TYPENAME") // CoreCLR class to handle lifetime and provide a simpler API surface class coreclr { public: // static /// <summary> /// Get a CoreCLR instance /// </summary> /// <returns>S_OK if newly created and needs initialization, S_FALSE if already exists and no initialization needed, otherwise an error code</returns> /// <remarks> /// If a CoreCLR instance has already been created, the existing instance is returned. /// If the <paramref name="path"/> is not supplied, the 'CORE_ROOT' environment variable is used. /// </remarks> static HRESULT GetCoreClrInstance(_Outptr_ coreclr **instance, _In_opt_z_ const WCHAR *path = nullptr); /// <summary> /// Populate the supplied string with a delimited string of TPA assemblies in from the supplied directory path. /// </summary> /// <remarks> /// If <paramref name="dir"/> is not supplied, the 'CORE_ROOT' environment variable is used. /// </remarks> static HRESULT CreateTpaList(_Inout_ std::string &tpaList, _In_opt_z_ const WCHAR *dir = nullptr); public: coreclr(_Inout_ AutoModule hmod); coreclr(_In_ const coreclr &) = delete; coreclr& operator=(_In_ const coreclr &) = delete; coreclr(_Inout_ coreclr &&) = delete; coreclr& operator=(_Inout_ coreclr &&) = delete; ~coreclr(); // See exported function 'coreclr_initialize' from coreclr library HRESULT Initialize( _In_ int propertyCount, _In_reads_(propertyCount) const char **keys, _In_reads_(propertyCount) const char **values, _In_opt_z_ const char *appDomainName = nullptr); // See exported function 'coreclr_create_delegate' from coreclr library HRESULT CreateDelegate( _In_z_ const char *assembly, _In_z_ const char *type, _In_z_ const char *method, _Out_ void **del); private: AutoModule _hmod; bool _attached; void *_clrInst; uint32_t _appDomainId; coreclr_initialize_ptr _initialize; coreclr_create_delegate_ptr _create_delegate; coreclr_shutdown_ptr _shutdown; }; #endif /* _CORESHIM_H_ */
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #ifndef _CORESHIM_H_ #define _CORESHIM_H_ // Platform #define NOMINMAX #include <Windows.h> #include <combaseapi.h> // Standard library #include <utility> #include <string> #include <cstdint> #include <cassert> // CoreCLR #include <palclr.h> #include <coreclrhost.h> #include <minipal/utils.h> #define WCHAR wchar_t #define RETURN_IF_FAILED(exp) { hr = (exp); if (FAILED(hr)) { assert(false && #exp); return hr; } } template < typename T, T DEFAULT, void(*RELEASE)(T) > struct AutoClass { T c; AutoClass() : c{ DEFAULT } { } AutoClass(_Inout_ T t) : c{ t } { } AutoClass(_In_ const AutoClass&) = delete; AutoClass& operator=(_In_ const AutoClass&) = delete; AutoClass(_Inout_ AutoClass &&other) : c{ other.Detach() } { } AutoClass& operator=(_Inout_ AutoClass &&other) { Attach(other.Detach()); } ~AutoClass() { Attach(DEFAULT); } operator T() { return c; } T* operator &() { return &c; } void Attach(_In_opt_ T cm) { RELEASE(c); c = cm; } T Detach() { T tmp = c; c = DEFAULT; return tmp; } }; inline void ReleaseHandle(_In_ HANDLE h) { if (h != nullptr && h != INVALID_HANDLE_VALUE) ::CloseHandle(h); } using AutoHandle = AutoClass<HANDLE, nullptr, &ReleaseHandle>; inline void ReleaseFindFile(_In_ HANDLE h) { if (h != nullptr) ::FindClose(h); } using AutoFindFile = AutoClass<HANDLE, nullptr, &ReleaseFindFile>; inline void ReleaseModule(_In_ HMODULE m) { if (m != nullptr) ::FreeLibrary(m); } using AutoModule = AutoClass<HMODULE, nullptr, &ReleaseModule>; namespace Utility { /// <summary> /// Get the supplied environment variable. /// </summary> HRESULT TryGetEnvVar(_In_z_ const WCHAR *env, _Inout_ std::wstring &envVar); /// <summary> /// Get the CoreShim directory. /// </summary> HRESULT GetCoreShimDirectory(_Inout_ std::string &dir); HRESULT GetCoreShimDirectory(_Inout_ std::wstring &dir); } // CoreShim environment variables used to indicate what assembly/type tuple // to load during COM activation. #define COMACT_ASSEMBLYNAME_ENVVAR W("CORESHIM_COMACT_ASSEMBLYNAME") #define COMACT_TYPENAME_ENVVAR W("CORESHIM_COMACT_TYPENAME") // CoreCLR class to handle lifetime and provide a simpler API surface class coreclr { public: // static /// <summary> /// Get a CoreCLR instance /// </summary> /// <returns>S_OK if newly created and needs initialization, S_FALSE if already exists and no initialization needed, otherwise an error code</returns> /// <remarks> /// If a CoreCLR instance has already been created, the existing instance is returned. /// If the <paramref name="path"/> is not supplied, the 'CORE_ROOT' environment variable is used. /// </remarks> static HRESULT GetCoreClrInstance(_Outptr_ coreclr **instance, _In_opt_z_ const WCHAR *path = nullptr); /// <summary> /// Populate the supplied string with a delimited string of TPA assemblies in from the supplied directory path. /// </summary> /// <remarks> /// If <paramref name="dir"/> is not supplied, the 'CORE_ROOT' environment variable is used. /// </remarks> static HRESULT CreateTpaList(_Inout_ std::string &tpaList, _In_opt_z_ const WCHAR *dir = nullptr); public: coreclr(_Inout_ AutoModule hmod); coreclr(_In_ const coreclr &) = delete; coreclr& operator=(_In_ const coreclr &) = delete; coreclr(_Inout_ coreclr &&) = delete; coreclr& operator=(_Inout_ coreclr &&) = delete; ~coreclr(); // See exported function 'coreclr_initialize' from coreclr library HRESULT Initialize( _In_ int propertyCount, _In_reads_(propertyCount) const char **keys, _In_reads_(propertyCount) const char **values, _In_opt_z_ const char *appDomainName = nullptr); // See exported function 'coreclr_create_delegate' from coreclr library HRESULT CreateDelegate( _In_z_ const char *assembly, _In_z_ const char *type, _In_z_ const char *method, _Out_ void **del); private: AutoModule _hmod; bool _attached; void *_clrInst; uint32_t _appDomainId; coreclr_initialize_ptr _initialize; coreclr_create_delegate_ptr _create_delegate; coreclr_shutdown_ptr _shutdown; }; #endif /* _CORESHIM_H_ */
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/mono/mono/metadata/debug-helpers.c
/** * \file * * Author: * Mono Project (http://www.mono-project.com) * * Copyright (C) 2005-2008 Novell, Inc. (http://www.novell.com) * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #include <config.h> #include <string.h> #include "mono/metadata/tokentype.h" #include "mono/metadata/opcodes.h" #include "mono/metadata/metadata-internals.h" #include "mono/metadata/class-internals.h" #include "mono/metadata/object-internals.h" #include "mono/metadata/mono-endian.h" #include "mono/metadata/debug-helpers.h" #include "mono/metadata/tabledefs.h" #include "mono/metadata/appdomain.h" #include "mono/metadata/abi-details.h" #ifdef MONO_CLASS_DEF_PRIVATE /* Rationale: we want the functions in this file to work even when everything * is broken. They may be called from a debugger session, for example. If * MonoClass getters include assertions or trigger class loading, we don't want * that kicked off by a call to one of the functions in here. */ #define REALLY_INCLUDE_CLASS_DEF 1 #include <mono/metadata/class-private-definition.h> #undef REALLY_INCLUDE_CLASS_DEF #endif struct MonoMethodDesc { char *name_space; char *klass; char *name; char *args; guint num_args; gboolean include_namespace, klass_glob, name_glob; }; // This, instead of an array of pointers, to optimize away a pointer and a relocation per string. #define MSGSTRFIELD(line) MSGSTRFIELD1(line) #define MSGSTRFIELD1(line) str##line static const struct msgstr_t { #define WRAPPER(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)]; #include "wrapper-types.h" #undef WRAPPER } opstr = { #define WRAPPER(a,b) b, #include "wrapper-types.h" #undef WRAPPER }; static const gint16 opidx [] = { #define WRAPPER(a,b) offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)), #include "wrapper-types.h" #undef WRAPPER }; const char* mono_wrapper_type_to_str (guint32 wrapper_type) { g_assert (wrapper_type < MONO_WRAPPER_NUM); return (const char*)&opstr + opidx [wrapper_type]; } static void append_class_name (GString *res, MonoClass *klass, gboolean include_namespace) { if (!klass) { g_string_append (res, "Unknown"); return; } if (klass->nested_in) { append_class_name (res, klass->nested_in, include_namespace); g_string_append_c (res, '/'); } if (include_namespace && *(klass->name_space)) { g_string_append (res, klass->name_space); g_string_append_c (res, '.'); } g_string_append (res, klass->name); } static MonoClass* find_system_class (const char *name) { if (!strcmp (name, "void")) return mono_defaults.void_class; else if (!strcmp (name, "char")) return mono_defaults.char_class; else if (!strcmp (name, "bool")) return mono_defaults.boolean_class; else if (!strcmp (name, "byte")) return mono_defaults.byte_class; else if (!strcmp (name, "sbyte")) return mono_defaults.sbyte_class; else if (!strcmp (name, "uint16")) return mono_defaults.uint16_class; else if (!strcmp (name, "int16")) return mono_defaults.int16_class; else if (!strcmp (name, "uint")) return mono_defaults.uint32_class; else if (!strcmp (name, "int")) return mono_defaults.int32_class; else if (!strcmp (name, "ulong")) return mono_defaults.uint64_class; else if (!strcmp (name, "long")) return mono_defaults.int64_class; else if (!strcmp (name, "uintptr")) return mono_defaults.uint_class; else if (!strcmp (name, "intptr")) return mono_defaults.int_class; else if (!strcmp (name, "single")) return mono_defaults.single_class; else if (!strcmp (name, "double")) return mono_defaults.double_class; else if (!strcmp (name, "string")) return mono_defaults.string_class; else if (!strcmp (name, "object")) return mono_defaults.object_class; else return NULL; } static void mono_custom_modifiers_get_desc (GString *res, const MonoType *type, gboolean include_namespace) { ERROR_DECL (error); int count = mono_type_custom_modifier_count (type); for (int i = 0; i < count; ++i) { gboolean required; MonoType *cmod_type = mono_type_get_custom_modifier (type, i, &required, error); mono_error_assert_ok (error); if (required) g_string_append (res, " modreq("); else g_string_append (res, " modopt("); mono_type_get_desc (res, cmod_type, include_namespace); g_string_append (res, ")"); } } void mono_type_get_desc (GString *res, MonoType *type, gboolean include_namespace) { int i; switch (type->type) { case MONO_TYPE_VOID: g_string_append (res, "void"); break; case MONO_TYPE_CHAR: g_string_append (res, "char"); break; case MONO_TYPE_BOOLEAN: g_string_append (res, "bool"); break; case MONO_TYPE_U1: g_string_append (res, "byte"); break; case MONO_TYPE_I1: g_string_append (res, "sbyte"); break; case MONO_TYPE_U2: g_string_append (res, "uint16"); break; case MONO_TYPE_I2: g_string_append (res, "int16"); break; case MONO_TYPE_U4: g_string_append (res, "uint"); break; case MONO_TYPE_I4: g_string_append (res, "int"); break; case MONO_TYPE_U8: g_string_append (res, "ulong"); break; case MONO_TYPE_I8: g_string_append (res, "long"); break; case MONO_TYPE_FNPTR: /* who cares for the exact signature? */ g_string_append (res, "*()"); break; case MONO_TYPE_U: g_string_append (res, "uintptr"); break; case MONO_TYPE_I: g_string_append (res, "intptr"); break; case MONO_TYPE_R4: g_string_append (res, "single"); break; case MONO_TYPE_R8: g_string_append (res, "double"); break; case MONO_TYPE_STRING: g_string_append (res, "string"); break; case MONO_TYPE_OBJECT: g_string_append (res, "object"); break; case MONO_TYPE_PTR: mono_type_get_desc (res, type->data.type, include_namespace); g_string_append_c (res, '*'); break; case MONO_TYPE_ARRAY: mono_type_get_desc (res, &type->data.array->eklass->_byval_arg, include_namespace); g_string_append_c (res, '['); for (i = 1; i < type->data.array->rank; ++i) g_string_append_c (res, ','); g_string_append_c (res, ']'); break; case MONO_TYPE_SZARRAY: mono_type_get_desc (res, &type->data.klass->_byval_arg, include_namespace); g_string_append (res, "[]"); break; case MONO_TYPE_CLASS: case MONO_TYPE_VALUETYPE: append_class_name (res, type->data.klass, include_namespace); break; case MONO_TYPE_GENERICINST: { MonoGenericContext *context; mono_type_get_desc (res, &type->data.generic_class->container_class->_byval_arg, include_namespace); g_string_append (res, "<"); context = &type->data.generic_class->context; if (context->class_inst) { for (i = 0; i < context->class_inst->type_argc; ++i) { if (i > 0) g_string_append (res, ", "); mono_type_get_desc (res, context->class_inst->type_argv [i], include_namespace); } } if (context->method_inst) { if (context->class_inst) g_string_append (res, "; "); for (i = 0; i < context->method_inst->type_argc; ++i) { if (i > 0) g_string_append (res, ", "); mono_type_get_desc (res, context->method_inst->type_argv [i], include_namespace); } } g_string_append (res, ">"); break; } case MONO_TYPE_VAR: case MONO_TYPE_MVAR: if (type->data.generic_param) { const char *name = mono_generic_param_name (type->data.generic_param); if (name) g_string_append (res, name); else g_string_append_printf (res, "%s%d", type->type == MONO_TYPE_VAR ? "!" : "!!", mono_generic_param_num (type->data.generic_param)); } else { g_string_append (res, "<unknown>"); } break; case MONO_TYPE_TYPEDBYREF: g_string_append (res, "typedbyref"); break; default: break; } if (type->has_cmods) { mono_custom_modifiers_get_desc (res, type, include_namespace); } if (m_type_is_byref (type)) g_string_append_c (res, '&'); } /** * mono_type_full_name: */ char* mono_type_full_name (MonoType *type) { GString *str; str = g_string_new (""); mono_type_get_desc (str, type, TRUE); return g_string_free (str, FALSE); } /** * mono_signature_get_desc: */ char* mono_signature_get_desc (MonoMethodSignature *sig, gboolean include_namespace) { int i; char *result; GString *res; if (!sig) return g_strdup ("<invalid signature>"); res = g_string_new (""); for (i = 0; i < sig->param_count; ++i) { if (i > 0) g_string_append_c (res, ','); mono_type_get_desc (res, sig->params [i], include_namespace); } result = res->str; g_string_free (res, FALSE); return result; } char* mono_signature_full_name (MonoMethodSignature *sig) { int i; char *result; GString *res; if (!sig) return g_strdup ("<invalid signature>"); res = g_string_new (""); mono_type_get_desc (res, sig->ret, TRUE); g_string_append_c (res, '('); for (i = 0; i < sig->param_count; ++i) { if (i > 0) g_string_append_c (res, ','); mono_type_get_desc (res, sig->params [i], TRUE); } g_string_append_c (res, ')'); result = res->str; g_string_free (res, FALSE); return result; } void mono_ginst_get_desc (GString *str, MonoGenericInst *ginst) { int i; for (i = 0; i < ginst->type_argc; ++i) { if (i > 0) g_string_append (str, ", "); mono_type_get_desc (str, ginst->type_argv [i], TRUE); } } char* mono_context_get_desc (MonoGenericContext *context) { GString *str; char *res; str = g_string_new (""); g_string_append (str, "<"); if (context->class_inst) mono_ginst_get_desc (str, context->class_inst); if (context->method_inst) { if (context->class_inst) g_string_append (str, "; "); mono_ginst_get_desc (str, context->method_inst); } g_string_append (str, ">"); res = g_strdup (str->str); g_string_free (str, TRUE); return res; } /** * mono_method_desc_new: * \param name the method name. * \param include_namespace whether the name includes a namespace or not. * * Creates a method description for \p name, which conforms to the following * specification: * * <code>[namespace.]classname:methodname[(args...)]</code> * * in all the loaded assemblies. * * Both classname and methodname can contain <code>*</code> which matches anything. * * \returns a parsed representation of the method description. */ MonoMethodDesc* mono_method_desc_new (const char *name, gboolean include_namespace) { MonoMethodDesc *result; char *class_name, *class_nspace, *method_name, *use_args, *end; int use_namespace; int generic_delim_stack; class_nspace = g_strdup (name); use_args = strchr (class_nspace, '('); if (use_args) { /* Allow a ' ' between the method name and the signature */ if (use_args > class_nspace && use_args [-1] == ' ') use_args [-1] = 0; *use_args++ = 0; end = strchr (use_args, ')'); if (!end) { g_free (class_nspace); return NULL; } *end = 0; } method_name = strrchr (class_nspace, ':'); if (!method_name) { g_free (class_nspace); return NULL; } /* allow two :: to separate the method name */ if (method_name != class_nspace && method_name [-1] == ':') method_name [-1] = 0; *method_name++ = 0; class_name = strrchr (class_nspace, '.'); if (class_name) { *class_name++ = 0; use_namespace = 1; } else { class_name = class_nspace; use_namespace = 0; } result = g_new0 (MonoMethodDesc, 1); result->include_namespace = include_namespace; result->name = method_name; result->klass = class_name; result->name_space = use_namespace? class_nspace: NULL; result->args = use_args? use_args: NULL; if (strstr (result->name, "*")) result->name_glob = TRUE; if (strstr (result->klass, "*")) result->klass_glob = TRUE; if (use_args) { end = use_args; if (*end) result->num_args = 1; generic_delim_stack = 0; while (*end) { if (*end == '<') generic_delim_stack++; else if (*end == '>') generic_delim_stack--; if (*end == ',' && generic_delim_stack == 0) result->num_args++; ++end; } } return result; } /** * mono_method_desc_from_method: */ MonoMethodDesc* mono_method_desc_from_method (MonoMethod *method) { MonoMethodDesc *result; result = g_new0 (MonoMethodDesc, 1); result->include_namespace = TRUE; result->name = g_strdup (method->name); result->klass = g_strdup (method->klass->name); result->name_space = g_strdup (method->klass->name_space); return result; } /** * mono_method_desc_free: * \param desc method description to be released * Releases the \c MonoMethodDesc object \p desc. */ void mono_method_desc_free (MonoMethodDesc *desc) { if (desc->name_space) g_free (desc->name_space); else if (desc->klass) g_free (desc->klass); g_free (desc); } /** * mono_method_desc_match: * \param desc \c MonoMethoDescription * \param method \c MonoMethod to test * * Determines whether the specified \p method matches the provided \p desc description. * * namespace and class are supposed to match already if this function is used. * \returns TRUE if the method matches the description, FALSE otherwise. */ gboolean mono_method_desc_match (MonoMethodDesc *desc, MonoMethod *method) { char *sig; gboolean name_match; if (desc->name_glob && !strcmp (desc->name, "*")) return TRUE; #if 0 /* FIXME: implement g_pattern_match_simple in eglib */ if (desc->name_glob && g_pattern_match_simple (desc->name, method->name)) return TRUE; #endif name_match = strcmp (desc->name, method->name) == 0; if (!name_match) return FALSE; if (!desc->args) return TRUE; if (desc->num_args != mono_method_signature_internal (method)->param_count) return FALSE; sig = mono_signature_get_desc (mono_method_signature_internal (method), desc->include_namespace); if (strcmp (sig, desc->args)) { g_free (sig); return FALSE; } g_free (sig); return TRUE; } static const char * my_strrchr (const char *str, char ch, int *len) { int pos; for (pos = (*len)-1; pos >= 0; pos--) { if (str [pos] != ch) continue; *len = pos; return str + pos; } return NULL; } static gboolean match_class (MonoMethodDesc *desc, int pos, MonoClass *klass) { const char *p; gboolean is_terminal = TRUE; if (desc->klass_glob && !strcmp (desc->klass, "*")) return TRUE; #ifndef _EGLIB_MAJOR if (desc->klass_glob && g_pattern_match_simple (desc->klass, klass->name)) return TRUE; #endif if (desc->klass[pos] == '/') is_terminal = FALSE; p = my_strrchr (desc->klass, '/', &pos); if (!p) { if (is_terminal && strcmp (desc->klass, klass->name)) return FALSE; if (!is_terminal && strncmp (desc->klass, klass->name, pos)) return FALSE; if (desc->name_space && strcmp (desc->name_space, klass->name_space)) return FALSE; return TRUE; } if (strcmp (p+1, klass->name)) return FALSE; if (!klass->nested_in) return FALSE; return match_class (desc, pos, klass->nested_in); } /** * mono_method_desc_is_full: */ gboolean mono_method_desc_is_full (MonoMethodDesc *desc) { return desc->klass && desc->klass[0] != '\0'; } /** * mono_method_desc_full_match: * \param desc A method description that you created with mono_method_desc_new * \param method a MonoMethod instance that you want to match against * * This method is used to check whether the method matches the provided * description, by making sure that the method matches both the class and the method parameters. * * \returns TRUE if the specified method matches the specified description, FALSE otherwise. */ gboolean mono_method_desc_full_match (MonoMethodDesc *desc, MonoMethod *method) { if (!desc) return FALSE; if (!desc->klass) return FALSE; if (!match_class (desc, strlen (desc->klass), method->klass)) return FALSE; return mono_method_desc_match (desc, method); } /** * mono_method_desc_search_in_class: */ MonoMethod* mono_method_desc_search_in_class (MonoMethodDesc *desc, MonoClass *klass) { MonoMethod* m; gpointer iter = NULL; while ((m = mono_class_get_methods (klass, &iter))) if (mono_method_desc_match (desc, m)) return m; return NULL; } /** * mono_method_desc_search_in_image: */ MonoMethod* mono_method_desc_search_in_image (MonoMethodDesc *desc, MonoImage *image) { MonoClass *klass; const MonoTableInfo *methods; MonoMethod *method; int i; /* Handle short names for system classes */ if (!desc->name_space && image == mono_defaults.corlib) { klass = find_system_class (desc->klass); if (klass) return mono_method_desc_search_in_class (desc, klass); } if (desc->name_space && desc->klass) { klass = mono_class_try_load_from_name (image, desc->name_space, desc->klass); if (!klass) return NULL; return mono_method_desc_search_in_class (desc, klass); } /* FIXME: Is this call necessary? We don't use its result. */ mono_image_get_table_info (image, MONO_TABLE_TYPEDEF); methods = mono_image_get_table_info (image, MONO_TABLE_METHOD); for (i = 0; i < mono_table_info_get_rows (methods); ++i) { ERROR_DECL (error); guint32 token = mono_metadata_decode_row_col (methods, i, MONO_METHOD_NAME); const char *n = mono_metadata_string_heap (image, token); if (strcmp (n, desc->name)) continue; method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL, NULL, error); if (!method) { mono_error_cleanup (error); continue; } if (mono_method_desc_full_match (desc, method)) return method; } return NULL; } static const unsigned char* dis_one (GString *str, MonoDisHelper *dh, MonoMethod *method, const unsigned char *ip, const unsigned char *end) { ERROR_DECL (error); MonoMethodHeader *header = mono_method_get_header_checked (method, error); const MonoOpcode *opcode; guint32 label, token; gint32 sval; int i; char *tmp; const unsigned char* il_code; if (!header) { g_string_append_printf (str, "could not disassemble, bad header due to %s", mono_error_get_message (error)); mono_error_cleanup (error); return end; } il_code = mono_method_header_get_code (header, NULL, NULL); label = ip - il_code; if (dh->indenter) { tmp = dh->indenter (dh, method, label); g_string_append (str, tmp); g_free (tmp); } if (dh->label_format) g_string_append_printf (str, dh->label_format, label); i = mono_opcode_value (&ip, end); ip++; opcode = &mono_opcodes [i]; g_string_append_printf (str, "%-10s", mono_opcode_name (i)); switch (opcode->argument) { case MonoInlineNone: break; case MonoInlineType: case MonoInlineField: case MonoInlineMethod: case MonoInlineTok: case MonoInlineSig: token = read32 (ip); if (dh->tokener) { tmp = dh->tokener (dh, method, token); g_string_append (str, tmp); g_free (tmp); } else { g_string_append_printf (str, "0x%08x", token); } ip += 4; break; case MonoInlineString: { const char *blob; char *s; size_t len2; char *blob2 = NULL; if (!image_is_dynamic (method->klass->image) && !method_is_dynamic (method)) { token = read32 (ip); blob = mono_metadata_user_string (method->klass->image, mono_metadata_token_index (token)); len2 = mono_metadata_decode_blob_size (blob, &blob); len2 >>= 1; #ifdef NO_UNALIGNED_ACCESS /* The blob might not be 2 byte aligned */ blob2 = g_malloc ((len2 * 2) + 1); memcpy (blob2, blob, len2 * 2); #else blob2 = (char*)blob; #endif #if G_BYTE_ORDER != G_LITTLE_ENDIAN { guint16 *buf = g_new (guint16, len2 + 1); int i; for (i = 0; i < len2; ++i) buf [i] = GUINT16_FROM_LE (((guint16*)blob2) [i]); s = g_utf16_to_utf8 (buf, len2, NULL, NULL, NULL); g_free (buf); } #else s = g_utf16_to_utf8 ((gunichar2*)blob2, len2, NULL, NULL, NULL); #endif g_string_append_printf (str, "\"%s\"", s); g_free (s); if (blob != blob2) g_free (blob2); } ip += 4; break; } case MonoInlineVar: g_string_append_printf (str, "%d", read16 (ip)); ip += 2; break; case MonoShortInlineVar: g_string_append_printf (str, "%d", (*ip)); ip ++; break; case MonoInlineBrTarget: sval = read32 (ip); ip += 4; if (dh->label_target) g_string_append_printf (str, dh->label_target, ip + sval - il_code); else g_string_append_printf (str, "%d", sval); break; case MonoShortInlineBrTarget: sval = *(const signed char*)ip; ip ++; if (dh->label_target) g_string_append_printf (str, dh->label_target, ip + sval - il_code); else g_string_append_printf (str, "%d", sval); break; case MonoInlineSwitch: { const unsigned char *end; sval = read32 (ip); ip += 4; end = ip + sval * 4; g_string_append_c (str, '('); for (i = 0; i < sval; ++i) { if (i > 0) g_string_append (str, ", "); label = read32 (ip); if (dh->label_target) g_string_append_printf (str, dh->label_target, end + label - il_code); else g_string_append_printf (str, "%d", label); ip += 4; } g_string_append_c (str, ')'); break; } case MonoInlineR: { double r; readr8 (ip, &r); g_string_append_printf (str, "%g", r); ip += 8; break; } case MonoShortInlineR: { float r; readr4 (ip, &r); g_string_append_printf (str, "%g", r); ip += 4; break; } case MonoInlineI: g_string_append_printf (str, "%d", (gint32)read32 (ip)); ip += 4; break; case MonoShortInlineI: g_string_append_printf (str, "%d", *(const signed char*)ip); ip ++; break; case MonoInlineI8: ip += 8; break; default: g_assert_not_reached (); } if (dh->newline) g_string_append (str, dh->newline); mono_metadata_free_mh (header); return ip; } static MonoDisHelper default_dh = { "\n", "IL_%04x: ", /* label_format */ "IL_%04x", /* label_target */ NULL, /* indenter */ NULL, /* tokener */ NULL /* user data */ }; /** * mono_disasm_code_one: */ char* mono_disasm_code_one (MonoDisHelper *dh, MonoMethod *method, const guchar *ip, const guchar **endp) { char *result; GString *res = g_string_new (""); if (!dh) dh = &default_dh; /* set ip + 2 as the end: this is just a debugging method */ ip = dis_one (res, dh, method, ip, ip + 2); if (endp) *endp = ip; result = res->str; g_string_free (res, FALSE); return result; } /** * mono_disasm_code: */ char* mono_disasm_code (MonoDisHelper *dh, MonoMethod *method, const guchar *ip, const guchar* end) { char *result; GString *res = g_string_new (""); if (!dh) dh = &default_dh; while (ip < end) { ip = dis_one (res, dh, method, ip, end); } result = res->str; g_string_free (res, FALSE); return result; } /** * mono_field_full_name: * \param field field to retrieve information for * \returns the full name for the field, made up of the namespace, type name and the field name. */ char * mono_field_full_name (MonoClassField *field) { char *res; const char *nspace = m_field_get_parent (field)->name_space; res = g_strdup_printf ("%s%s%s:%s", nspace, *nspace ? "." : "", m_field_get_parent (field)->name, mono_field_get_name (field)); return res; } char * mono_method_get_name_full (MonoMethod *method, gboolean signature, gboolean ret, MonoTypeNameFormat format) { char *res; char wrapper [64]; char *klass_desc; char *inst_desc = NULL; ERROR_DECL (error); const char *class_method_separator = ":"; const char *method_sig_space = " "; if (format == MONO_TYPE_NAME_FORMAT_REFLECTION) { class_method_separator = "."; method_sig_space = ""; } if (format == MONO_TYPE_NAME_FORMAT_IL) klass_desc = mono_type_full_name (&method->klass->_byval_arg); else klass_desc = mono_type_get_name_full (&method->klass->_byval_arg, format); if (method->is_inflated && ((MonoMethodInflated*)method)->context.method_inst) { GString *str = g_string_new (""); if (format == MONO_TYPE_NAME_FORMAT_IL) g_string_append (str, "<"); else g_string_append (str, "["); mono_ginst_get_desc (str, ((MonoMethodInflated*)method)->context.method_inst); if (format == MONO_TYPE_NAME_FORMAT_IL) g_string_append_c (str, '>'); else g_string_append_c (str, ']'); inst_desc = str->str; g_string_free (str, FALSE); } else if (method->is_generic) { MonoGenericContainer *container = mono_method_get_generic_container (method); GString *str = g_string_new (""); if (format == MONO_TYPE_NAME_FORMAT_IL) g_string_append (str, "<"); else g_string_append (str, "["); mono_ginst_get_desc (str, container->context.method_inst); if (format == MONO_TYPE_NAME_FORMAT_IL) g_string_append_c (str, '>'); else g_string_append_c (str, ']'); inst_desc = str->str; g_string_free (str, FALSE); } if (method->wrapper_type != MONO_WRAPPER_NONE) sprintf (wrapper, "(wrapper %s) ", mono_wrapper_type_to_str (method->wrapper_type)); else strcpy (wrapper, ""); if (signature) { MonoMethodSignature *sig = mono_method_signature_checked (method, error); char *tmpsig; if (!is_ok (error)) { tmpsig = g_strdup_printf ("<unable to load signature>"); mono_error_cleanup (error); } else { tmpsig = mono_signature_get_desc (sig, TRUE); } if (method->wrapper_type != MONO_WRAPPER_NONE) sprintf (wrapper, "(wrapper %s) ", mono_wrapper_type_to_str (method->wrapper_type)); else strcpy (wrapper, ""); if (ret && sig) { char *ret_str = mono_type_full_name (sig->ret); res = g_strdup_printf ("%s%s %s%s%s%s%s(%s)", wrapper, ret_str, klass_desc, class_method_separator, method->name, inst_desc ? inst_desc : "", method_sig_space, tmpsig); g_free (ret_str); } else { res = g_strdup_printf ("%s%s%s%s%s%s(%s)", wrapper, klass_desc, class_method_separator, method->name, inst_desc ? inst_desc : "", method_sig_space, tmpsig); } g_free (tmpsig); } else { res = g_strdup_printf ("%s%s%s%s%s", wrapper, klass_desc, class_method_separator, method->name, inst_desc ? inst_desc : ""); } g_free (klass_desc); g_free (inst_desc); return res; } /** * mono_method_full_name: */ char * mono_method_full_name (MonoMethod *method, gboolean signature) { char *res; MONO_ENTER_GC_UNSAFE; res = mono_method_get_name_full (method, signature, FALSE, MONO_TYPE_NAME_FORMAT_IL); MONO_EXIT_GC_UNSAFE; return res; } char * mono_method_get_full_name (MonoMethod *method) { return mono_method_get_name_full (method, TRUE, TRUE, MONO_TYPE_NAME_FORMAT_IL); } /** * mono_method_get_reflection_name: * * Returns the name of the method, including signature, using the same formating as reflection. */ char * mono_method_get_reflection_name (MonoMethod *method) { return mono_method_get_name_full (method, TRUE, FALSE, MONO_TYPE_NAME_FORMAT_REFLECTION); } static const char* print_name_space (MonoClass *klass) { if (klass->nested_in) { print_name_space (klass->nested_in); g_print ("%s", klass->nested_in->name); return "/"; } if (klass->name_space [0]) { g_print ("%s", klass->name_space); return "."; } return ""; } /** * mono_object_describe: * * Prints to stdout a small description of the object \p obj. * For use in a debugger. */ void mono_object_describe (MonoObject *obj) { ERROR_DECL (error); MonoClass* klass; const char* sep; if (!obj) { g_print ("(null)\n"); return; } klass = mono_object_class (obj); if (klass == mono_defaults.string_class) { char *utf8 = mono_string_to_utf8_checked_internal ((MonoString*)obj, error); mono_error_cleanup (error); /* FIXME don't swallow the error */ if (utf8 && strlen (utf8) > 60) { utf8 [57] = '.'; utf8 [58] = '.'; utf8 [59] = '.'; utf8 [60] = 0; } if (utf8) { g_print ("String at %p, length: %d, '%s'\n", obj, mono_string_length_internal ((MonoString*) obj), utf8); } else { g_print ("String at %p, length: %d, unable to decode UTF16\n", obj, mono_string_length_internal ((MonoString*) obj)); } g_free (utf8); } else if (klass->rank) { MonoArray *array = (MonoArray*)obj; sep = print_name_space (klass); g_print ("%s%s", sep, klass->name); g_print (" at %p, rank: %d, length: %d\n", obj, klass->rank, (int)mono_array_length_internal (array)); } else { sep = print_name_space (klass); g_print ("%s%s", sep, klass->name); g_print (" object at %p (klass: %p)\n", obj, klass); } } static void print_field_value (const char *field_ptr, MonoClassField *field, int type_offset) { MonoType *type; g_print ("At %p (ofs: %2d) %s: ", field_ptr, field->offset + type_offset, mono_field_get_name (field)); type = mono_type_get_underlying_type (field->type); switch (type->type) { case MONO_TYPE_I: case MONO_TYPE_U: case MONO_TYPE_PTR: case MONO_TYPE_FNPTR: g_print ("%p\n", *(const void**)field_ptr); break; case MONO_TYPE_STRING: case MONO_TYPE_SZARRAY: case MONO_TYPE_CLASS: case MONO_TYPE_OBJECT: case MONO_TYPE_ARRAY: mono_object_describe (*(MonoObject**)field_ptr); break; case MONO_TYPE_GENERICINST: if (!mono_type_generic_inst_is_valuetype (type)) { mono_object_describe (*(MonoObject**)field_ptr); break; } else { /* fall through */ } case MONO_TYPE_VALUETYPE: { MonoClass *k = mono_class_from_mono_type_internal (type); g_print ("%s ValueType (type: %p) at %p\n", k->name, k, field_ptr); break; } case MONO_TYPE_I1: g_print ("%d\n", *(gint8*)field_ptr); break; case MONO_TYPE_U1: g_print ("%d\n", *(guint8*)field_ptr); break; case MONO_TYPE_I2: g_print ("%d\n", *(gint16*)field_ptr); break; case MONO_TYPE_U2: g_print ("%d\n", *(guint16*)field_ptr); break; case MONO_TYPE_I4: g_print ("%d\n", *(gint32*)field_ptr); break; case MONO_TYPE_U4: g_print ("%u\n", *(guint32*)field_ptr); break; case MONO_TYPE_I8: g_print ("%" PRId64 "\n", *(gint64*)field_ptr); break; case MONO_TYPE_U8: g_print ("%" PRIu64 "\n", *(guint64*)field_ptr); break; case MONO_TYPE_R4: g_print ("%f\n", *(gfloat*)field_ptr); break; case MONO_TYPE_R8: g_print ("%f\n", *(gdouble*)field_ptr); break; case MONO_TYPE_BOOLEAN: g_print ("%s (%d)\n", *(guint8*)field_ptr? "True": "False", *(guint8*)field_ptr); break; case MONO_TYPE_CHAR: g_print ("'%c' (%d 0x%04x)\n", *(guint16*)field_ptr, *(guint16*)field_ptr, *(guint16*)field_ptr); break; default: g_assert_not_reached (); break; } } static void objval_describe (MonoClass *klass, const char *addr) { MonoClassField *field; MonoClass *p; const char *field_ptr; gssize type_offset = 0; if (klass->valuetype) type_offset = - MONO_ABI_SIZEOF (MonoObject); for (p = klass; p != NULL; p = p->parent) { gpointer iter = NULL; int printed_header = FALSE; while ((field = mono_class_get_fields_internal (p, &iter))) { if (field->type->attrs & (FIELD_ATTRIBUTE_STATIC | FIELD_ATTRIBUTE_HAS_FIELD_RVA)) continue; if (p != klass && !printed_header) { const char *sep; g_print ("In class "); sep = print_name_space (p); g_print ("%s%s:\n", sep, p->name); printed_header = TRUE; } field_ptr = (const char*)addr + field->offset + type_offset; print_field_value (field_ptr, field, type_offset); } } } /** * mono_object_describe_fields: * * Prints to stdout a small description of each field of the object \p obj. * For use in a debugger. */ void mono_object_describe_fields (MonoObject *obj) { MonoClass *klass = mono_object_class (obj); objval_describe (klass, (char*)obj); } /** * mono_value_describe_fields: * * Prints to stdout a small description of each field of the value type * stored at \p addr of type \p klass. * For use in a debugger. */ void mono_value_describe_fields (MonoClass* klass, const char* addr) { objval_describe (klass, addr); } /** * mono_class_describe_statics: * * Prints to stdout a small description of each static field of the type \p klass * in the current application domain. * For use in a debugger. */ void mono_class_describe_statics (MonoClass* klass) { ERROR_DECL (error); MonoClassField *field; MonoClass *p; const char *field_ptr; MonoVTable *vtable = mono_class_vtable_checked (klass, error); const char *addr; if (!vtable || !is_ok (error)) { mono_error_cleanup (error); return; } if (!(addr = (const char *)mono_vtable_get_static_field_data (vtable))) return; for (p = klass; p != NULL; p = p->parent) { gpointer iter = NULL; while ((field = mono_class_get_fields_internal (p, &iter))) { if (field->type->attrs & FIELD_ATTRIBUTE_LITERAL) continue; if (!(field->type->attrs & (FIELD_ATTRIBUTE_STATIC | FIELD_ATTRIBUTE_HAS_FIELD_RVA))) continue; field_ptr = (const char*)addr + field->offset; print_field_value (field_ptr, field, 0); } } } /** * mono_print_method_code * \param method: a pointer to the method * * This method is used from a debugger to print the code of the method. * * This prints the IL code of the method in the standard output. */ void mono_method_print_code (MonoMethod *method) { ERROR_DECL (error); char *code; MonoMethodHeader *header = mono_method_get_header_checked (method, error); if (!header) { printf ("METHOD HEADER NOT FOUND DUE TO: %s\n", mono_error_get_message (error)); mono_error_cleanup (error); return; } code = mono_disasm_code (0, method, header->code, header->code + header->code_size); printf ("CODE FOR %s:\n%s\n", mono_method_full_name (method, TRUE), code); g_free (code); }
/** * \file * * Author: * Mono Project (http://www.mono-project.com) * * Copyright (C) 2005-2008 Novell, Inc. (http://www.novell.com) * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #include <config.h> #include <string.h> #include "mono/metadata/tokentype.h" #include "mono/metadata/opcodes.h" #include "mono/metadata/metadata-internals.h" #include "mono/metadata/class-internals.h" #include "mono/metadata/object-internals.h" #include "mono/metadata/mono-endian.h" #include "mono/metadata/debug-helpers.h" #include "mono/metadata/tabledefs.h" #include "mono/metadata/appdomain.h" #include "mono/metadata/abi-details.h" #ifdef MONO_CLASS_DEF_PRIVATE /* Rationale: we want the functions in this file to work even when everything * is broken. They may be called from a debugger session, for example. If * MonoClass getters include assertions or trigger class loading, we don't want * that kicked off by a call to one of the functions in here. */ #define REALLY_INCLUDE_CLASS_DEF 1 #include <mono/metadata/class-private-definition.h> #undef REALLY_INCLUDE_CLASS_DEF #endif struct MonoMethodDesc { char *name_space; char *klass; char *name; char *args; guint num_args; gboolean include_namespace, klass_glob, name_glob; }; // This, instead of an array of pointers, to optimize away a pointer and a relocation per string. #define MSGSTRFIELD(line) MSGSTRFIELD1(line) #define MSGSTRFIELD1(line) str##line static const struct msgstr_t { #define WRAPPER(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)]; #include "wrapper-types.h" #undef WRAPPER } opstr = { #define WRAPPER(a,b) b, #include "wrapper-types.h" #undef WRAPPER }; static const gint16 opidx [] = { #define WRAPPER(a,b) offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)), #include "wrapper-types.h" #undef WRAPPER }; const char* mono_wrapper_type_to_str (guint32 wrapper_type) { g_assert (wrapper_type < MONO_WRAPPER_NUM); return (const char*)&opstr + opidx [wrapper_type]; } static void append_class_name (GString *res, MonoClass *klass, gboolean include_namespace) { if (!klass) { g_string_append (res, "Unknown"); return; } if (klass->nested_in) { append_class_name (res, klass->nested_in, include_namespace); g_string_append_c (res, '/'); } if (include_namespace && *(klass->name_space)) { g_string_append (res, klass->name_space); g_string_append_c (res, '.'); } g_string_append (res, klass->name); } static MonoClass* find_system_class (const char *name) { if (!strcmp (name, "void")) return mono_defaults.void_class; else if (!strcmp (name, "char")) return mono_defaults.char_class; else if (!strcmp (name, "bool")) return mono_defaults.boolean_class; else if (!strcmp (name, "byte")) return mono_defaults.byte_class; else if (!strcmp (name, "sbyte")) return mono_defaults.sbyte_class; else if (!strcmp (name, "uint16")) return mono_defaults.uint16_class; else if (!strcmp (name, "int16")) return mono_defaults.int16_class; else if (!strcmp (name, "uint")) return mono_defaults.uint32_class; else if (!strcmp (name, "int")) return mono_defaults.int32_class; else if (!strcmp (name, "ulong")) return mono_defaults.uint64_class; else if (!strcmp (name, "long")) return mono_defaults.int64_class; else if (!strcmp (name, "uintptr")) return mono_defaults.uint_class; else if (!strcmp (name, "intptr")) return mono_defaults.int_class; else if (!strcmp (name, "single")) return mono_defaults.single_class; else if (!strcmp (name, "double")) return mono_defaults.double_class; else if (!strcmp (name, "string")) return mono_defaults.string_class; else if (!strcmp (name, "object")) return mono_defaults.object_class; else return NULL; } static void mono_custom_modifiers_get_desc (GString *res, const MonoType *type, gboolean include_namespace) { ERROR_DECL (error); int count = mono_type_custom_modifier_count (type); for (int i = 0; i < count; ++i) { gboolean required; MonoType *cmod_type = mono_type_get_custom_modifier (type, i, &required, error); mono_error_assert_ok (error); if (required) g_string_append (res, " modreq("); else g_string_append (res, " modopt("); mono_type_get_desc (res, cmod_type, include_namespace); g_string_append (res, ")"); } } void mono_type_get_desc (GString *res, MonoType *type, gboolean include_namespace) { int i; switch (type->type) { case MONO_TYPE_VOID: g_string_append (res, "void"); break; case MONO_TYPE_CHAR: g_string_append (res, "char"); break; case MONO_TYPE_BOOLEAN: g_string_append (res, "bool"); break; case MONO_TYPE_U1: g_string_append (res, "byte"); break; case MONO_TYPE_I1: g_string_append (res, "sbyte"); break; case MONO_TYPE_U2: g_string_append (res, "uint16"); break; case MONO_TYPE_I2: g_string_append (res, "int16"); break; case MONO_TYPE_U4: g_string_append (res, "uint"); break; case MONO_TYPE_I4: g_string_append (res, "int"); break; case MONO_TYPE_U8: g_string_append (res, "ulong"); break; case MONO_TYPE_I8: g_string_append (res, "long"); break; case MONO_TYPE_FNPTR: /* who cares for the exact signature? */ g_string_append (res, "*()"); break; case MONO_TYPE_U: g_string_append (res, "uintptr"); break; case MONO_TYPE_I: g_string_append (res, "intptr"); break; case MONO_TYPE_R4: g_string_append (res, "single"); break; case MONO_TYPE_R8: g_string_append (res, "double"); break; case MONO_TYPE_STRING: g_string_append (res, "string"); break; case MONO_TYPE_OBJECT: g_string_append (res, "object"); break; case MONO_TYPE_PTR: mono_type_get_desc (res, type->data.type, include_namespace); g_string_append_c (res, '*'); break; case MONO_TYPE_ARRAY: mono_type_get_desc (res, &type->data.array->eklass->_byval_arg, include_namespace); g_string_append_c (res, '['); for (i = 1; i < type->data.array->rank; ++i) g_string_append_c (res, ','); g_string_append_c (res, ']'); break; case MONO_TYPE_SZARRAY: mono_type_get_desc (res, &type->data.klass->_byval_arg, include_namespace); g_string_append (res, "[]"); break; case MONO_TYPE_CLASS: case MONO_TYPE_VALUETYPE: append_class_name (res, type->data.klass, include_namespace); break; case MONO_TYPE_GENERICINST: { MonoGenericContext *context; mono_type_get_desc (res, &type->data.generic_class->container_class->_byval_arg, include_namespace); g_string_append (res, "<"); context = &type->data.generic_class->context; if (context->class_inst) { for (i = 0; i < context->class_inst->type_argc; ++i) { if (i > 0) g_string_append (res, ", "); mono_type_get_desc (res, context->class_inst->type_argv [i], include_namespace); } } if (context->method_inst) { if (context->class_inst) g_string_append (res, "; "); for (i = 0; i < context->method_inst->type_argc; ++i) { if (i > 0) g_string_append (res, ", "); mono_type_get_desc (res, context->method_inst->type_argv [i], include_namespace); } } g_string_append (res, ">"); break; } case MONO_TYPE_VAR: case MONO_TYPE_MVAR: if (type->data.generic_param) { const char *name = mono_generic_param_name (type->data.generic_param); if (name) g_string_append (res, name); else g_string_append_printf (res, "%s%d", type->type == MONO_TYPE_VAR ? "!" : "!!", mono_generic_param_num (type->data.generic_param)); } else { g_string_append (res, "<unknown>"); } break; case MONO_TYPE_TYPEDBYREF: g_string_append (res, "typedbyref"); break; default: break; } if (type->has_cmods) { mono_custom_modifiers_get_desc (res, type, include_namespace); } if (m_type_is_byref (type)) g_string_append_c (res, '&'); } /** * mono_type_full_name: */ char* mono_type_full_name (MonoType *type) { GString *str; str = g_string_new (""); mono_type_get_desc (str, type, TRUE); return g_string_free (str, FALSE); } /** * mono_signature_get_desc: */ char* mono_signature_get_desc (MonoMethodSignature *sig, gboolean include_namespace) { int i; char *result; GString *res; if (!sig) return g_strdup ("<invalid signature>"); res = g_string_new (""); for (i = 0; i < sig->param_count; ++i) { if (i > 0) g_string_append_c (res, ','); mono_type_get_desc (res, sig->params [i], include_namespace); } result = res->str; g_string_free (res, FALSE); return result; } char* mono_signature_full_name (MonoMethodSignature *sig) { int i; char *result; GString *res; if (!sig) return g_strdup ("<invalid signature>"); res = g_string_new (""); mono_type_get_desc (res, sig->ret, TRUE); g_string_append_c (res, '('); for (i = 0; i < sig->param_count; ++i) { if (i > 0) g_string_append_c (res, ','); mono_type_get_desc (res, sig->params [i], TRUE); } g_string_append_c (res, ')'); result = res->str; g_string_free (res, FALSE); return result; } void mono_ginst_get_desc (GString *str, MonoGenericInst *ginst) { int i; for (i = 0; i < ginst->type_argc; ++i) { if (i > 0) g_string_append (str, ", "); mono_type_get_desc (str, ginst->type_argv [i], TRUE); } } char* mono_context_get_desc (MonoGenericContext *context) { GString *str; char *res; str = g_string_new (""); g_string_append (str, "<"); if (context->class_inst) mono_ginst_get_desc (str, context->class_inst); if (context->method_inst) { if (context->class_inst) g_string_append (str, "; "); mono_ginst_get_desc (str, context->method_inst); } g_string_append (str, ">"); res = g_strdup (str->str); g_string_free (str, TRUE); return res; } /** * mono_method_desc_new: * \param name the method name. * \param include_namespace whether the name includes a namespace or not. * * Creates a method description for \p name, which conforms to the following * specification: * * <code>[namespace.]classname:methodname[(args...)]</code> * * in all the loaded assemblies. * * Both classname and methodname can contain <code>*</code> which matches anything. * * \returns a parsed representation of the method description. */ MonoMethodDesc* mono_method_desc_new (const char *name, gboolean include_namespace) { MonoMethodDesc *result; char *class_name, *class_nspace, *method_name, *use_args, *end; int use_namespace; int generic_delim_stack; class_nspace = g_strdup (name); use_args = strchr (class_nspace, '('); if (use_args) { /* Allow a ' ' between the method name and the signature */ if (use_args > class_nspace && use_args [-1] == ' ') use_args [-1] = 0; *use_args++ = 0; end = strchr (use_args, ')'); if (!end) { g_free (class_nspace); return NULL; } *end = 0; } method_name = strrchr (class_nspace, ':'); if (!method_name) { g_free (class_nspace); return NULL; } /* allow two :: to separate the method name */ if (method_name != class_nspace && method_name [-1] == ':') method_name [-1] = 0; *method_name++ = 0; class_name = strrchr (class_nspace, '.'); if (class_name) { *class_name++ = 0; use_namespace = 1; } else { class_name = class_nspace; use_namespace = 0; } result = g_new0 (MonoMethodDesc, 1); result->include_namespace = include_namespace; result->name = method_name; result->klass = class_name; result->name_space = use_namespace? class_nspace: NULL; result->args = use_args? use_args: NULL; if (strstr (result->name, "*")) result->name_glob = TRUE; if (strstr (result->klass, "*")) result->klass_glob = TRUE; if (use_args) { end = use_args; if (*end) result->num_args = 1; generic_delim_stack = 0; while (*end) { if (*end == '<') generic_delim_stack++; else if (*end == '>') generic_delim_stack--; if (*end == ',' && generic_delim_stack == 0) result->num_args++; ++end; } } return result; } /** * mono_method_desc_from_method: */ MonoMethodDesc* mono_method_desc_from_method (MonoMethod *method) { MonoMethodDesc *result; result = g_new0 (MonoMethodDesc, 1); result->include_namespace = TRUE; result->name = g_strdup (method->name); result->klass = g_strdup (method->klass->name); result->name_space = g_strdup (method->klass->name_space); return result; } /** * mono_method_desc_free: * \param desc method description to be released * Releases the \c MonoMethodDesc object \p desc. */ void mono_method_desc_free (MonoMethodDesc *desc) { if (desc->name_space) g_free (desc->name_space); else if (desc->klass) g_free (desc->klass); g_free (desc); } /** * mono_method_desc_match: * \param desc \c MonoMethoDescription * \param method \c MonoMethod to test * * Determines whether the specified \p method matches the provided \p desc description. * * namespace and class are supposed to match already if this function is used. * \returns TRUE if the method matches the description, FALSE otherwise. */ gboolean mono_method_desc_match (MonoMethodDesc *desc, MonoMethod *method) { char *sig; gboolean name_match; if (desc->name_glob && !strcmp (desc->name, "*")) return TRUE; #if 0 /* FIXME: implement g_pattern_match_simple in eglib */ if (desc->name_glob && g_pattern_match_simple (desc->name, method->name)) return TRUE; #endif name_match = strcmp (desc->name, method->name) == 0; if (!name_match) return FALSE; if (!desc->args) return TRUE; if (desc->num_args != mono_method_signature_internal (method)->param_count) return FALSE; sig = mono_signature_get_desc (mono_method_signature_internal (method), desc->include_namespace); if (strcmp (sig, desc->args)) { g_free (sig); return FALSE; } g_free (sig); return TRUE; } static const char * my_strrchr (const char *str, char ch, int *len) { int pos; for (pos = (*len)-1; pos >= 0; pos--) { if (str [pos] != ch) continue; *len = pos; return str + pos; } return NULL; } static gboolean match_class (MonoMethodDesc *desc, int pos, MonoClass *klass) { const char *p; gboolean is_terminal = TRUE; if (desc->klass_glob && !strcmp (desc->klass, "*")) return TRUE; #ifndef _EGLIB_MAJOR if (desc->klass_glob && g_pattern_match_simple (desc->klass, klass->name)) return TRUE; #endif if (desc->klass[pos] == '/') is_terminal = FALSE; p = my_strrchr (desc->klass, '/', &pos); if (!p) { if (is_terminal && strcmp (desc->klass, klass->name)) return FALSE; if (!is_terminal && strncmp (desc->klass, klass->name, pos)) return FALSE; if (desc->name_space && strcmp (desc->name_space, klass->name_space)) return FALSE; return TRUE; } if (strcmp (p+1, klass->name)) return FALSE; if (!klass->nested_in) return FALSE; return match_class (desc, pos, klass->nested_in); } /** * mono_method_desc_is_full: */ gboolean mono_method_desc_is_full (MonoMethodDesc *desc) { return desc->klass && desc->klass[0] != '\0'; } /** * mono_method_desc_full_match: * \param desc A method description that you created with mono_method_desc_new * \param method a MonoMethod instance that you want to match against * * This method is used to check whether the method matches the provided * description, by making sure that the method matches both the class and the method parameters. * * \returns TRUE if the specified method matches the specified description, FALSE otherwise. */ gboolean mono_method_desc_full_match (MonoMethodDesc *desc, MonoMethod *method) { if (!desc) return FALSE; if (!desc->klass) return FALSE; if (!match_class (desc, strlen (desc->klass), method->klass)) return FALSE; return mono_method_desc_match (desc, method); } /** * mono_method_desc_search_in_class: */ MonoMethod* mono_method_desc_search_in_class (MonoMethodDesc *desc, MonoClass *klass) { MonoMethod* m; gpointer iter = NULL; while ((m = mono_class_get_methods (klass, &iter))) if (mono_method_desc_match (desc, m)) return m; return NULL; } /** * mono_method_desc_search_in_image: */ MonoMethod* mono_method_desc_search_in_image (MonoMethodDesc *desc, MonoImage *image) { MonoClass *klass; const MonoTableInfo *methods; MonoMethod *method; int i; /* Handle short names for system classes */ if (!desc->name_space && image == mono_defaults.corlib) { klass = find_system_class (desc->klass); if (klass) return mono_method_desc_search_in_class (desc, klass); } if (desc->name_space && desc->klass) { klass = mono_class_try_load_from_name (image, desc->name_space, desc->klass); if (!klass) return NULL; return mono_method_desc_search_in_class (desc, klass); } /* FIXME: Is this call necessary? We don't use its result. */ mono_image_get_table_info (image, MONO_TABLE_TYPEDEF); methods = mono_image_get_table_info (image, MONO_TABLE_METHOD); for (i = 0; i < mono_table_info_get_rows (methods); ++i) { ERROR_DECL (error); guint32 token = mono_metadata_decode_row_col (methods, i, MONO_METHOD_NAME); const char *n = mono_metadata_string_heap (image, token); if (strcmp (n, desc->name)) continue; method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL, NULL, error); if (!method) { mono_error_cleanup (error); continue; } if (mono_method_desc_full_match (desc, method)) return method; } return NULL; } static const unsigned char* dis_one (GString *str, MonoDisHelper *dh, MonoMethod *method, const unsigned char *ip, const unsigned char *end) { ERROR_DECL (error); MonoMethodHeader *header = mono_method_get_header_checked (method, error); const MonoOpcode *opcode; guint32 label, token; gint32 sval; int i; char *tmp; const unsigned char* il_code; if (!header) { g_string_append_printf (str, "could not disassemble, bad header due to %s", mono_error_get_message (error)); mono_error_cleanup (error); return end; } il_code = mono_method_header_get_code (header, NULL, NULL); label = ip - il_code; if (dh->indenter) { tmp = dh->indenter (dh, method, label); g_string_append (str, tmp); g_free (tmp); } if (dh->label_format) g_string_append_printf (str, dh->label_format, label); i = mono_opcode_value (&ip, end); ip++; opcode = &mono_opcodes [i]; g_string_append_printf (str, "%-10s", mono_opcode_name (i)); switch (opcode->argument) { case MonoInlineNone: break; case MonoInlineType: case MonoInlineField: case MonoInlineMethod: case MonoInlineTok: case MonoInlineSig: token = read32 (ip); if (dh->tokener) { tmp = dh->tokener (dh, method, token); g_string_append (str, tmp); g_free (tmp); } else { g_string_append_printf (str, "0x%08x", token); } ip += 4; break; case MonoInlineString: { const char *blob; char *s; size_t len2; char *blob2 = NULL; if (!image_is_dynamic (method->klass->image) && !method_is_dynamic (method)) { token = read32 (ip); blob = mono_metadata_user_string (method->klass->image, mono_metadata_token_index (token)); len2 = mono_metadata_decode_blob_size (blob, &blob); len2 >>= 1; #ifdef NO_UNALIGNED_ACCESS /* The blob might not be 2 byte aligned */ blob2 = g_malloc ((len2 * 2) + 1); memcpy (blob2, blob, len2 * 2); #else blob2 = (char*)blob; #endif #if G_BYTE_ORDER != G_LITTLE_ENDIAN { guint16 *buf = g_new (guint16, len2 + 1); int i; for (i = 0; i < len2; ++i) buf [i] = GUINT16_FROM_LE (((guint16*)blob2) [i]); s = g_utf16_to_utf8 (buf, len2, NULL, NULL, NULL); g_free (buf); } #else s = g_utf16_to_utf8 ((gunichar2*)blob2, len2, NULL, NULL, NULL); #endif g_string_append_printf (str, "\"%s\"", s); g_free (s); if (blob != blob2) g_free (blob2); } ip += 4; break; } case MonoInlineVar: g_string_append_printf (str, "%d", read16 (ip)); ip += 2; break; case MonoShortInlineVar: g_string_append_printf (str, "%d", (*ip)); ip ++; break; case MonoInlineBrTarget: sval = read32 (ip); ip += 4; if (dh->label_target) g_string_append_printf (str, dh->label_target, ip + sval - il_code); else g_string_append_printf (str, "%d", sval); break; case MonoShortInlineBrTarget: sval = *(const signed char*)ip; ip ++; if (dh->label_target) g_string_append_printf (str, dh->label_target, ip + sval - il_code); else g_string_append_printf (str, "%d", sval); break; case MonoInlineSwitch: { const unsigned char *end; sval = read32 (ip); ip += 4; end = ip + sval * 4; g_string_append_c (str, '('); for (i = 0; i < sval; ++i) { if (i > 0) g_string_append (str, ", "); label = read32 (ip); if (dh->label_target) g_string_append_printf (str, dh->label_target, end + label - il_code); else g_string_append_printf (str, "%d", label); ip += 4; } g_string_append_c (str, ')'); break; } case MonoInlineR: { double r; readr8 (ip, &r); g_string_append_printf (str, "%g", r); ip += 8; break; } case MonoShortInlineR: { float r; readr4 (ip, &r); g_string_append_printf (str, "%g", r); ip += 4; break; } case MonoInlineI: g_string_append_printf (str, "%d", (gint32)read32 (ip)); ip += 4; break; case MonoShortInlineI: g_string_append_printf (str, "%d", *(const signed char*)ip); ip ++; break; case MonoInlineI8: ip += 8; break; default: g_assert_not_reached (); } if (dh->newline) g_string_append (str, dh->newline); mono_metadata_free_mh (header); return ip; } static MonoDisHelper default_dh = { "\n", "IL_%04x: ", /* label_format */ "IL_%04x", /* label_target */ NULL, /* indenter */ NULL, /* tokener */ NULL /* user data */ }; /** * mono_disasm_code_one: */ char* mono_disasm_code_one (MonoDisHelper *dh, MonoMethod *method, const guchar *ip, const guchar **endp) { char *result; GString *res = g_string_new (""); if (!dh) dh = &default_dh; /* set ip + 2 as the end: this is just a debugging method */ ip = dis_one (res, dh, method, ip, ip + 2); if (endp) *endp = ip; result = res->str; g_string_free (res, FALSE); return result; } /** * mono_disasm_code: */ char* mono_disasm_code (MonoDisHelper *dh, MonoMethod *method, const guchar *ip, const guchar* end) { char *result; GString *res = g_string_new (""); if (!dh) dh = &default_dh; while (ip < end) { ip = dis_one (res, dh, method, ip, end); } result = res->str; g_string_free (res, FALSE); return result; } /** * mono_field_full_name: * \param field field to retrieve information for * \returns the full name for the field, made up of the namespace, type name and the field name. */ char * mono_field_full_name (MonoClassField *field) { char *res; const char *nspace = m_field_get_parent (field)->name_space; res = g_strdup_printf ("%s%s%s:%s", nspace, *nspace ? "." : "", m_field_get_parent (field)->name, mono_field_get_name (field)); return res; } char * mono_method_get_name_full (MonoMethod *method, gboolean signature, gboolean ret, MonoTypeNameFormat format) { char *res; char wrapper [64]; char *klass_desc; char *inst_desc = NULL; ERROR_DECL (error); const char *class_method_separator = ":"; const char *method_sig_space = " "; if (format == MONO_TYPE_NAME_FORMAT_REFLECTION) { class_method_separator = "."; method_sig_space = ""; } if (format == MONO_TYPE_NAME_FORMAT_IL) klass_desc = mono_type_full_name (&method->klass->_byval_arg); else klass_desc = mono_type_get_name_full (&method->klass->_byval_arg, format); if (method->is_inflated && ((MonoMethodInflated*)method)->context.method_inst) { GString *str = g_string_new (""); if (format == MONO_TYPE_NAME_FORMAT_IL) g_string_append (str, "<"); else g_string_append (str, "["); mono_ginst_get_desc (str, ((MonoMethodInflated*)method)->context.method_inst); if (format == MONO_TYPE_NAME_FORMAT_IL) g_string_append_c (str, '>'); else g_string_append_c (str, ']'); inst_desc = str->str; g_string_free (str, FALSE); } else if (method->is_generic) { MonoGenericContainer *container = mono_method_get_generic_container (method); GString *str = g_string_new (""); if (format == MONO_TYPE_NAME_FORMAT_IL) g_string_append (str, "<"); else g_string_append (str, "["); mono_ginst_get_desc (str, container->context.method_inst); if (format == MONO_TYPE_NAME_FORMAT_IL) g_string_append_c (str, '>'); else g_string_append_c (str, ']'); inst_desc = str->str; g_string_free (str, FALSE); } if (method->wrapper_type != MONO_WRAPPER_NONE) sprintf (wrapper, "(wrapper %s) ", mono_wrapper_type_to_str (method->wrapper_type)); else strcpy (wrapper, ""); if (signature) { MonoMethodSignature *sig = mono_method_signature_checked (method, error); char *tmpsig; if (!is_ok (error)) { tmpsig = g_strdup_printf ("<unable to load signature>"); mono_error_cleanup (error); } else { tmpsig = mono_signature_get_desc (sig, TRUE); } if (method->wrapper_type != MONO_WRAPPER_NONE) sprintf (wrapper, "(wrapper %s) ", mono_wrapper_type_to_str (method->wrapper_type)); else strcpy (wrapper, ""); if (ret && sig) { char *ret_str = mono_type_full_name (sig->ret); res = g_strdup_printf ("%s%s %s%s%s%s%s(%s)", wrapper, ret_str, klass_desc, class_method_separator, method->name, inst_desc ? inst_desc : "", method_sig_space, tmpsig); g_free (ret_str); } else { res = g_strdup_printf ("%s%s%s%s%s%s(%s)", wrapper, klass_desc, class_method_separator, method->name, inst_desc ? inst_desc : "", method_sig_space, tmpsig); } g_free (tmpsig); } else { res = g_strdup_printf ("%s%s%s%s%s", wrapper, klass_desc, class_method_separator, method->name, inst_desc ? inst_desc : ""); } g_free (klass_desc); g_free (inst_desc); return res; } /** * mono_method_full_name: */ char * mono_method_full_name (MonoMethod *method, gboolean signature) { char *res; MONO_ENTER_GC_UNSAFE; res = mono_method_get_name_full (method, signature, FALSE, MONO_TYPE_NAME_FORMAT_IL); MONO_EXIT_GC_UNSAFE; return res; } char * mono_method_get_full_name (MonoMethod *method) { return mono_method_get_name_full (method, TRUE, TRUE, MONO_TYPE_NAME_FORMAT_IL); } /** * mono_method_get_reflection_name: * * Returns the name of the method, including signature, using the same formating as reflection. */ char * mono_method_get_reflection_name (MonoMethod *method) { return mono_method_get_name_full (method, TRUE, FALSE, MONO_TYPE_NAME_FORMAT_REFLECTION); } static const char* print_name_space (MonoClass *klass) { if (klass->nested_in) { print_name_space (klass->nested_in); g_print ("%s", klass->nested_in->name); return "/"; } if (klass->name_space [0]) { g_print ("%s", klass->name_space); return "."; } return ""; } /** * mono_object_describe: * * Prints to stdout a small description of the object \p obj. * For use in a debugger. */ void mono_object_describe (MonoObject *obj) { ERROR_DECL (error); MonoClass* klass; const char* sep; if (!obj) { g_print ("(null)\n"); return; } klass = mono_object_class (obj); if (klass == mono_defaults.string_class) { char *utf8 = mono_string_to_utf8_checked_internal ((MonoString*)obj, error); mono_error_cleanup (error); /* FIXME don't swallow the error */ if (utf8 && strlen (utf8) > 60) { utf8 [57] = '.'; utf8 [58] = '.'; utf8 [59] = '.'; utf8 [60] = 0; } if (utf8) { g_print ("String at %p, length: %d, '%s'\n", obj, mono_string_length_internal ((MonoString*) obj), utf8); } else { g_print ("String at %p, length: %d, unable to decode UTF16\n", obj, mono_string_length_internal ((MonoString*) obj)); } g_free (utf8); } else if (klass->rank) { MonoArray *array = (MonoArray*)obj; sep = print_name_space (klass); g_print ("%s%s", sep, klass->name); g_print (" at %p, rank: %d, length: %d\n", obj, klass->rank, (int)mono_array_length_internal (array)); } else { sep = print_name_space (klass); g_print ("%s%s", sep, klass->name); g_print (" object at %p (klass: %p)\n", obj, klass); } } static void print_field_value (const char *field_ptr, MonoClassField *field, int type_offset) { MonoType *type; g_print ("At %p (ofs: %2d) %s: ", field_ptr, field->offset + type_offset, mono_field_get_name (field)); type = mono_type_get_underlying_type (field->type); switch (type->type) { case MONO_TYPE_I: case MONO_TYPE_U: case MONO_TYPE_PTR: case MONO_TYPE_FNPTR: g_print ("%p\n", *(const void**)field_ptr); break; case MONO_TYPE_STRING: case MONO_TYPE_SZARRAY: case MONO_TYPE_CLASS: case MONO_TYPE_OBJECT: case MONO_TYPE_ARRAY: mono_object_describe (*(MonoObject**)field_ptr); break; case MONO_TYPE_GENERICINST: if (!mono_type_generic_inst_is_valuetype (type)) { mono_object_describe (*(MonoObject**)field_ptr); break; } else { /* fall through */ } case MONO_TYPE_VALUETYPE: { MonoClass *k = mono_class_from_mono_type_internal (type); g_print ("%s ValueType (type: %p) at %p\n", k->name, k, field_ptr); break; } case MONO_TYPE_I1: g_print ("%d\n", *(gint8*)field_ptr); break; case MONO_TYPE_U1: g_print ("%d\n", *(guint8*)field_ptr); break; case MONO_TYPE_I2: g_print ("%d\n", *(gint16*)field_ptr); break; case MONO_TYPE_U2: g_print ("%d\n", *(guint16*)field_ptr); break; case MONO_TYPE_I4: g_print ("%d\n", *(gint32*)field_ptr); break; case MONO_TYPE_U4: g_print ("%u\n", *(guint32*)field_ptr); break; case MONO_TYPE_I8: g_print ("%" PRId64 "\n", *(gint64*)field_ptr); break; case MONO_TYPE_U8: g_print ("%" PRIu64 "\n", *(guint64*)field_ptr); break; case MONO_TYPE_R4: g_print ("%f\n", *(gfloat*)field_ptr); break; case MONO_TYPE_R8: g_print ("%f\n", *(gdouble*)field_ptr); break; case MONO_TYPE_BOOLEAN: g_print ("%s (%d)\n", *(guint8*)field_ptr? "True": "False", *(guint8*)field_ptr); break; case MONO_TYPE_CHAR: g_print ("'%c' (%d 0x%04x)\n", *(guint16*)field_ptr, *(guint16*)field_ptr, *(guint16*)field_ptr); break; default: g_assert_not_reached (); break; } } static void objval_describe (MonoClass *klass, const char *addr) { MonoClassField *field; MonoClass *p; const char *field_ptr; gssize type_offset = 0; if (klass->valuetype) type_offset = - MONO_ABI_SIZEOF (MonoObject); for (p = klass; p != NULL; p = p->parent) { gpointer iter = NULL; int printed_header = FALSE; while ((field = mono_class_get_fields_internal (p, &iter))) { if (field->type->attrs & (FIELD_ATTRIBUTE_STATIC | FIELD_ATTRIBUTE_HAS_FIELD_RVA)) continue; if (p != klass && !printed_header) { const char *sep; g_print ("In class "); sep = print_name_space (p); g_print ("%s%s:\n", sep, p->name); printed_header = TRUE; } field_ptr = (const char*)addr + field->offset + type_offset; print_field_value (field_ptr, field, type_offset); } } } /** * mono_object_describe_fields: * * Prints to stdout a small description of each field of the object \p obj. * For use in a debugger. */ void mono_object_describe_fields (MonoObject *obj) { MonoClass *klass = mono_object_class (obj); objval_describe (klass, (char*)obj); } /** * mono_value_describe_fields: * * Prints to stdout a small description of each field of the value type * stored at \p addr of type \p klass. * For use in a debugger. */ void mono_value_describe_fields (MonoClass* klass, const char* addr) { objval_describe (klass, addr); } /** * mono_class_describe_statics: * * Prints to stdout a small description of each static field of the type \p klass * in the current application domain. * For use in a debugger. */ void mono_class_describe_statics (MonoClass* klass) { ERROR_DECL (error); MonoClassField *field; MonoClass *p; const char *field_ptr; MonoVTable *vtable = mono_class_vtable_checked (klass, error); const char *addr; if (!vtable || !is_ok (error)) { mono_error_cleanup (error); return; } if (!(addr = (const char *)mono_vtable_get_static_field_data (vtable))) return; for (p = klass; p != NULL; p = p->parent) { gpointer iter = NULL; while ((field = mono_class_get_fields_internal (p, &iter))) { if (field->type->attrs & FIELD_ATTRIBUTE_LITERAL) continue; if (!(field->type->attrs & (FIELD_ATTRIBUTE_STATIC | FIELD_ATTRIBUTE_HAS_FIELD_RVA))) continue; field_ptr = (const char*)addr + field->offset; print_field_value (field_ptr, field, 0); } } } /** * mono_print_method_code * \param method: a pointer to the method * * This method is used from a debugger to print the code of the method. * * This prints the IL code of the method in the standard output. */ void mono_method_print_code (MonoMethod *method) { ERROR_DECL (error); char *code; MonoMethodHeader *header = mono_method_get_header_checked (method, error); if (!header) { printf ("METHOD HEADER NOT FOUND DUE TO: %s\n", mono_error_get_message (error)); mono_error_cleanup (error); return; } code = mono_disasm_code (0, method, header->code, header->code + header->code_size); printf ("CODE FOR %s:\n%s\n", mono_method_full_name (method, TRUE), code); g_free (code); }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/vm/synch.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // #ifndef __Synch_h__ #define __Synch_h__ enum WaitMode { WaitMode_None =0x0, WaitMode_Alertable = 0x1, // Can be waken by APC. May pumping message. WaitMode_IgnoreSyncCtx = 0x2, // Dispatch to synchronization context if existed. WaitMode_InDeadlock = 0x4, // The wait can be terminated by host's deadlock detection }; struct PendingSync; class CRWLock; class CLREventBase { public: CLREventBase() { LIMITED_METHOD_CONTRACT; m_handle = INVALID_HANDLE_VALUE; m_dwFlags = 0; } // Create an Event that is host aware void CreateAutoEvent(BOOL bInitialState); void CreateManualEvent(BOOL bInitialState); // Non-throwing variants of the functions above BOOL CreateAutoEventNoThrow(BOOL bInitialState); BOOL CreateManualEventNoThrow(BOOL bInitialState); void CreateMonitorEvent(SIZE_T Cookie); // robust against initialization races - for exclusive use by AwareLock // Create an Event that is not host aware void CreateOSAutoEvent (BOOL bInitialState); void CreateOSManualEvent (BOOL bInitialState); // Non-throwing variants of the functions above BOOL CreateOSAutoEventNoThrow (BOOL bInitialState); BOOL CreateOSManualEventNoThrow (BOOL bInitialState); void CloseEvent(); BOOL IsValid() const { LIMITED_METHOD_CONTRACT; return m_handle != INVALID_HANDLE_VALUE; } BOOL IsMonitorEventAllocated() { LIMITED_METHOD_CONTRACT; return m_dwFlags & CLREVENT_FLAGS_MONITOREVENT_ALLOCATED; } #ifndef DACCESS_COMPILE HANDLE GetHandleUNHOSTED() { LIMITED_METHOD_CONTRACT; return m_handle; } #endif // DACCESS_COMPILE BOOL Set(); void SetMonitorEvent(); // robust against races - for exclusive use by AwareLock BOOL Reset(); DWORD Wait(DWORD dwMilliseconds, BOOL bAlertable, PendingSync *syncState=NULL); DWORD WaitEx(DWORD dwMilliseconds, WaitMode mode, PendingSync *syncState=NULL); protected: HANDLE m_handle; private: enum { CLREVENT_FLAGS_AUTO_EVENT = 0x0001, CLREVENT_FLAGS_OS_EVENT = 0x0002, CLREVENT_FLAGS_IN_DEADLOCK_DETECTION = 0x0004, CLREVENT_FLAGS_MONITOREVENT_ALLOCATED = 0x0008, CLREVENT_FLAGS_MONITOREVENT_SIGNALLED = 0x0010, CLREVENT_FLAGS_STATIC = 0x0020, // Several bits unused; }; Volatile<DWORD> m_dwFlags; BOOL IsAutoEvent() { LIMITED_METHOD_CONTRACT; return m_dwFlags & CLREVENT_FLAGS_AUTO_EVENT; } void SetAutoEvent () { LIMITED_METHOD_CONTRACT; // cannot use `|=' operator on `Volatile<DWORD>' m_dwFlags = m_dwFlags | CLREVENT_FLAGS_AUTO_EVENT; } BOOL IsOSEvent() { LIMITED_METHOD_CONTRACT; return m_dwFlags & CLREVENT_FLAGS_OS_EVENT; } void SetOSEvent () { LIMITED_METHOD_CONTRACT; // cannot use `|=' operator on `Volatile<DWORD>' m_dwFlags = m_dwFlags | CLREVENT_FLAGS_OS_EVENT; } BOOL IsInDeadlockDetection() { LIMITED_METHOD_CONTRACT; return m_dwFlags & CLREVENT_FLAGS_IN_DEADLOCK_DETECTION; } void SetInDeadlockDetection () { LIMITED_METHOD_CONTRACT; // cannot use `|=' operator on `Volatile<DWORD>' m_dwFlags = m_dwFlags | CLREVENT_FLAGS_IN_DEADLOCK_DETECTION; } }; class CLREvent : public CLREventBase { public: #ifndef DACCESS_COMPILE ~CLREvent() { WRAPPER_NO_CONTRACT; CloseEvent(); } #endif }; // CLREventStatic // Same as CLREvent, but intended to be used for global variables. // Instances may leak their handle, because of the order in which // global destructors are run. Note that you can still explicitly // call CloseHandle, which will indeed not leak the handle. class CLREventStatic : public CLREventBase { }; class CLRSemaphore { public: CLRSemaphore() : m_handle(INVALID_HANDLE_VALUE) { LIMITED_METHOD_CONTRACT; } ~CLRSemaphore() { WRAPPER_NO_CONTRACT; Close (); } void Create(DWORD dwInitial, DWORD dwMax); void Close(); BOOL IsValid() const { LIMITED_METHOD_CONTRACT; return m_handle != INVALID_HANDLE_VALUE; } DWORD Wait(DWORD dwMilliseconds, BOOL bAlertable); BOOL Release(LONG lReleaseCount, LONG* lpPreviouseCount); private: HANDLE m_handle; }; class CLRLifoSemaphore { private: struct Counts { union { struct { UINT32 signalCount; UINT16 waiterCount; UINT8 spinnerCount; UINT8 countOfWaitersSignaledToWake; }; UINT64 data; }; Counts(UINT64 data = 0) : data(data) { LIMITED_METHOD_CONTRACT; } operator UINT64() const { LIMITED_METHOD_CONTRACT; return data; } Counts operator -() const { LIMITED_METHOD_CONTRACT; return -(INT64)data; } Counts &operator =(UINT64 data) { LIMITED_METHOD_CONTRACT; this->data = data; return *this; } Counts VolatileLoadWithoutBarrier() const { LIMITED_METHOD_CONTRACT; return ::VolatileLoadWithoutBarrier(&data); } Counts CompareExchange(Counts toCounts, Counts fromCounts) { LIMITED_METHOD_CONTRACT; return (UINT64)InterlockedCompareExchange64((LONG64 *)&data, (LONG64)toCounts, (LONG64)fromCounts); } Counts ExchangeAdd(Counts toAdd) { LIMITED_METHOD_CONTRACT; return (UINT64)InterlockedExchangeAdd64((LONG64 *)&data, (LONG64)toAdd); } }; public: CLRLifoSemaphore() : m_handle(nullptr) { LIMITED_METHOD_CONTRACT; } ~CLRLifoSemaphore() { WRAPPER_NO_CONTRACT; Close(); } public: void Create(INT32 initialSignalCount, INT32 maximumSignalCount); void Close(); public: BOOL IsValid() const { LIMITED_METHOD_CONTRACT; return m_handle != nullptr; } private: bool WaitForSignal(DWORD timeoutMs); public: bool Wait(DWORD timeoutMs); bool Wait(DWORD timeoutMs, UINT32 spinCount, UINT32 processorCount); void Release(INT32 releaseCount); private: BYTE __padding1[MAX_CACHE_LINE_SIZE]; // padding to ensure that m_counts gets its own cache line // Take care to use 'm_counts.VolatileLoadWithoutBarrier()` when loading this value into a local variable that will be // reused. See AwareLock::m_lockState for details. Counts m_counts; BYTE __padding2[MAX_CACHE_LINE_SIZE]; // padding to ensure that m_counts gets its own cache line #if defined(DEBUG) UINT32 m_maximumSignalCount; #endif // _DEBUG && !TARGET_UNIX // When TARGET_UNIX is defined, this is a handle to an instance of the PAL's LIFO semaphore. When TARGET_UNIX is not // defined, this is a handle to an I/O completion port. HANDLE m_handle; }; class CLRMutex { public: CLRMutex() : m_handle(INVALID_HANDLE_VALUE) { LIMITED_METHOD_CONTRACT; } ~CLRMutex() { WRAPPER_NO_CONTRACT; Close (); } void Create(LPSECURITY_ATTRIBUTES lpMutexAttributes, BOOL bInitialOwner, LPCTSTR lpName); void Close(); BOOL IsValid() const { LIMITED_METHOD_CONTRACT; return m_handle != INVALID_HANDLE_VALUE; } DWORD Wait(DWORD dwMilliseconds, BOOL bAlertable); BOOL Release(); private: HANDLE m_handle; }; BOOL CLREventWaitWithTry(CLREventBase *pEvent, DWORD timeout, BOOL fAlertable, DWORD *pStatus); #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // #ifndef __Synch_h__ #define __Synch_h__ enum WaitMode { WaitMode_None =0x0, WaitMode_Alertable = 0x1, // Can be waken by APC. May pumping message. WaitMode_IgnoreSyncCtx = 0x2, // Dispatch to synchronization context if existed. WaitMode_InDeadlock = 0x4, // The wait can be terminated by host's deadlock detection }; struct PendingSync; class CRWLock; class CLREventBase { public: CLREventBase() { LIMITED_METHOD_CONTRACT; m_handle = INVALID_HANDLE_VALUE; m_dwFlags = 0; } // Create an Event that is host aware void CreateAutoEvent(BOOL bInitialState); void CreateManualEvent(BOOL bInitialState); // Non-throwing variants of the functions above BOOL CreateAutoEventNoThrow(BOOL bInitialState); BOOL CreateManualEventNoThrow(BOOL bInitialState); void CreateMonitorEvent(SIZE_T Cookie); // robust against initialization races - for exclusive use by AwareLock // Create an Event that is not host aware void CreateOSAutoEvent (BOOL bInitialState); void CreateOSManualEvent (BOOL bInitialState); // Non-throwing variants of the functions above BOOL CreateOSAutoEventNoThrow (BOOL bInitialState); BOOL CreateOSManualEventNoThrow (BOOL bInitialState); void CloseEvent(); BOOL IsValid() const { LIMITED_METHOD_CONTRACT; return m_handle != INVALID_HANDLE_VALUE; } BOOL IsMonitorEventAllocated() { LIMITED_METHOD_CONTRACT; return m_dwFlags & CLREVENT_FLAGS_MONITOREVENT_ALLOCATED; } #ifndef DACCESS_COMPILE HANDLE GetHandleUNHOSTED() { LIMITED_METHOD_CONTRACT; return m_handle; } #endif // DACCESS_COMPILE BOOL Set(); void SetMonitorEvent(); // robust against races - for exclusive use by AwareLock BOOL Reset(); DWORD Wait(DWORD dwMilliseconds, BOOL bAlertable, PendingSync *syncState=NULL); DWORD WaitEx(DWORD dwMilliseconds, WaitMode mode, PendingSync *syncState=NULL); protected: HANDLE m_handle; private: enum { CLREVENT_FLAGS_AUTO_EVENT = 0x0001, CLREVENT_FLAGS_OS_EVENT = 0x0002, CLREVENT_FLAGS_IN_DEADLOCK_DETECTION = 0x0004, CLREVENT_FLAGS_MONITOREVENT_ALLOCATED = 0x0008, CLREVENT_FLAGS_MONITOREVENT_SIGNALLED = 0x0010, CLREVENT_FLAGS_STATIC = 0x0020, // Several bits unused; }; Volatile<DWORD> m_dwFlags; BOOL IsAutoEvent() { LIMITED_METHOD_CONTRACT; return m_dwFlags & CLREVENT_FLAGS_AUTO_EVENT; } void SetAutoEvent () { LIMITED_METHOD_CONTRACT; // cannot use `|=' operator on `Volatile<DWORD>' m_dwFlags = m_dwFlags | CLREVENT_FLAGS_AUTO_EVENT; } BOOL IsOSEvent() { LIMITED_METHOD_CONTRACT; return m_dwFlags & CLREVENT_FLAGS_OS_EVENT; } void SetOSEvent () { LIMITED_METHOD_CONTRACT; // cannot use `|=' operator on `Volatile<DWORD>' m_dwFlags = m_dwFlags | CLREVENT_FLAGS_OS_EVENT; } BOOL IsInDeadlockDetection() { LIMITED_METHOD_CONTRACT; return m_dwFlags & CLREVENT_FLAGS_IN_DEADLOCK_DETECTION; } void SetInDeadlockDetection () { LIMITED_METHOD_CONTRACT; // cannot use `|=' operator on `Volatile<DWORD>' m_dwFlags = m_dwFlags | CLREVENT_FLAGS_IN_DEADLOCK_DETECTION; } }; class CLREvent : public CLREventBase { public: #ifndef DACCESS_COMPILE ~CLREvent() { WRAPPER_NO_CONTRACT; CloseEvent(); } #endif }; // CLREventStatic // Same as CLREvent, but intended to be used for global variables. // Instances may leak their handle, because of the order in which // global destructors are run. Note that you can still explicitly // call CloseHandle, which will indeed not leak the handle. class CLREventStatic : public CLREventBase { }; class CLRSemaphore { public: CLRSemaphore() : m_handle(INVALID_HANDLE_VALUE) { LIMITED_METHOD_CONTRACT; } ~CLRSemaphore() { WRAPPER_NO_CONTRACT; Close (); } void Create(DWORD dwInitial, DWORD dwMax); void Close(); BOOL IsValid() const { LIMITED_METHOD_CONTRACT; return m_handle != INVALID_HANDLE_VALUE; } DWORD Wait(DWORD dwMilliseconds, BOOL bAlertable); BOOL Release(LONG lReleaseCount, LONG* lpPreviouseCount); private: HANDLE m_handle; }; class CLRLifoSemaphore { private: struct Counts { union { struct { UINT32 signalCount; UINT16 waiterCount; UINT8 spinnerCount; UINT8 countOfWaitersSignaledToWake; }; UINT64 data; }; Counts(UINT64 data = 0) : data(data) { LIMITED_METHOD_CONTRACT; } operator UINT64() const { LIMITED_METHOD_CONTRACT; return data; } Counts operator -() const { LIMITED_METHOD_CONTRACT; return -(INT64)data; } Counts &operator =(UINT64 data) { LIMITED_METHOD_CONTRACT; this->data = data; return *this; } Counts VolatileLoadWithoutBarrier() const { LIMITED_METHOD_CONTRACT; return ::VolatileLoadWithoutBarrier(&data); } Counts CompareExchange(Counts toCounts, Counts fromCounts) { LIMITED_METHOD_CONTRACT; return (UINT64)InterlockedCompareExchange64((LONG64 *)&data, (LONG64)toCounts, (LONG64)fromCounts); } Counts ExchangeAdd(Counts toAdd) { LIMITED_METHOD_CONTRACT; return (UINT64)InterlockedExchangeAdd64((LONG64 *)&data, (LONG64)toAdd); } }; public: CLRLifoSemaphore() : m_handle(nullptr) { LIMITED_METHOD_CONTRACT; } ~CLRLifoSemaphore() { WRAPPER_NO_CONTRACT; Close(); } public: void Create(INT32 initialSignalCount, INT32 maximumSignalCount); void Close(); public: BOOL IsValid() const { LIMITED_METHOD_CONTRACT; return m_handle != nullptr; } private: bool WaitForSignal(DWORD timeoutMs); public: bool Wait(DWORD timeoutMs); bool Wait(DWORD timeoutMs, UINT32 spinCount, UINT32 processorCount); void Release(INT32 releaseCount); private: BYTE __padding1[MAX_CACHE_LINE_SIZE]; // padding to ensure that m_counts gets its own cache line // Take care to use 'm_counts.VolatileLoadWithoutBarrier()` when loading this value into a local variable that will be // reused. See AwareLock::m_lockState for details. Counts m_counts; BYTE __padding2[MAX_CACHE_LINE_SIZE]; // padding to ensure that m_counts gets its own cache line #if defined(DEBUG) UINT32 m_maximumSignalCount; #endif // _DEBUG && !TARGET_UNIX // When TARGET_UNIX is defined, this is a handle to an instance of the PAL's LIFO semaphore. When TARGET_UNIX is not // defined, this is a handle to an I/O completion port. HANDLE m_handle; }; class CLRMutex { public: CLRMutex() : m_handle(INVALID_HANDLE_VALUE) { LIMITED_METHOD_CONTRACT; } ~CLRMutex() { WRAPPER_NO_CONTRACT; Close (); } void Create(LPSECURITY_ATTRIBUTES lpMutexAttributes, BOOL bInitialOwner, LPCTSTR lpName); void Close(); BOOL IsValid() const { LIMITED_METHOD_CONTRACT; return m_handle != INVALID_HANDLE_VALUE; } DWORD Wait(DWORD dwMilliseconds, BOOL bAlertable); BOOL Release(); private: HANDLE m_handle; }; BOOL CLREventWaitWithTry(CLREventBase *pEvent, DWORD timeout, BOOL fAlertable, DWORD *pStatus); #endif
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/pal/src/include/pal/critsect.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*++ Module Name: include/pal/critsect.h Abstract: Header file for the critical sections functions. --*/ #ifndef _PAL_CRITSECT_H_ #define _PAL_CRITSECT_H_ #ifdef __cplusplus extern "C" { #endif // __cplusplus VOID InternalInitializeCriticalSection(CRITICAL_SECTION *pcs); VOID InternalDeleteCriticalSection(CRITICAL_SECTION *pcs); /* The following PALCEnterCriticalSection and PALCLeaveCriticalSection functions are intended to provide CorUnix's InternalEnterCriticalSection and InternalLeaveCriticalSection functionalities to legacy C code, which has no knowledge of CPalThread, classes and namespaces. */ VOID PALCEnterCriticalSection(CRITICAL_SECTION *pcs); VOID PALCLeaveCriticalSection(CRITICAL_SECTION *pcs); #ifdef __cplusplus } #endif // __cplusplus #endif /* _PAL_CRITSECT_H_ */
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*++ Module Name: include/pal/critsect.h Abstract: Header file for the critical sections functions. --*/ #ifndef _PAL_CRITSECT_H_ #define _PAL_CRITSECT_H_ #ifdef __cplusplus extern "C" { #endif // __cplusplus VOID InternalInitializeCriticalSection(CRITICAL_SECTION *pcs); VOID InternalDeleteCriticalSection(CRITICAL_SECTION *pcs); /* The following PALCEnterCriticalSection and PALCLeaveCriticalSection functions are intended to provide CorUnix's InternalEnterCriticalSection and InternalLeaveCriticalSection functionalities to legacy C code, which has no knowledge of CPalThread, classes and namespaces. */ VOID PALCEnterCriticalSection(CRITICAL_SECTION *pcs); VOID PALCLeaveCriticalSection(CRITICAL_SECTION *pcs); #ifdef __cplusplus } #endif // __cplusplus #endif /* _PAL_CRITSECT_H_ */
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/pal/src/libunwind/include/tdep-tilegx/libunwind_i.h
/* libunwind - a platform-independent unwind library Copyright (C) 2008 CodeSourcery Copyright (C) 2014 Tilera Corp. This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef TILEGX_LIBUNWIND_I_H #define TILEGX_LIBUNWIND_I_H /* Target-dependent definitions that are internal to libunwind but need to be shared with target-independent code. */ #include <stdlib.h> #include <libunwind.h> #include <stdatomic.h> # include "elf64.h" #include "mempool.h" #include "dwarf.h" typedef struct { /* no Tilegx-specific fast trace */ } unw_tdep_frame_t; struct unw_addr_space { struct unw_accessors acc; int big_endian; tilegx_abi_t abi; unsigned int addr_size; unw_caching_policy_t caching_policy; _Atomic uint32_t cache_generation; unw_word_t dyn_generation; /* see dyn-common.h */ unw_word_t dyn_info_list_addr; /* (cached) dyn_info_list_addr */ struct dwarf_rs_cache global_cache; struct unw_debug_frame_list *debug_frames; }; #define tdep_big_endian(as) ((as)->big_endian) struct cursor { struct dwarf_cursor dwarf; /* must be first */ unw_word_t sigcontext_addr; unw_word_t sigcontext_sp; unw_word_t sigcontext_pc; }; #define DWARF_GET_LOC(l) ((l).val) #ifndef UNW_REMOTE_ONLY typedef long tilegx_reg_t; #endif #ifdef UNW_LOCAL_ONLY #define DWARF_NULL_LOC DWARF_LOC (0, 0) #define DWARF_IS_NULL_LOC(l) (DWARF_GET_LOC (l) == 0) #define DWARF_LOC(r, t) ((dwarf_loc_t) { .val = (r) }) #define DWARF_IS_REG_LOC(l) 0 #define DWARF_REG_LOC(c,r) (DWARF_LOC((unw_word_t) (intptr_t) \ tdep_uc_addr((c)->as_arg, (r)), 0)) #define DWARF_MEM_LOC(c,m) DWARF_LOC ((m), 0) #define DWARF_FPREG_LOC(c,r) (DWARF_LOC((unw_word_t) (intptr_t) \ tdep_uc_addr((c)->as_arg, (r)), 0)) /* Tilegx has no FP. */ static inline int dwarf_getfp (struct dwarf_cursor *c, dwarf_loc_t loc, unw_fpreg_t *val) { Debug (1, "Tielgx has no fp!\n"); abort(); return 0; } static inline int dwarf_putfp (struct dwarf_cursor *c, dwarf_loc_t loc, unw_fpreg_t val) { Debug (1, "Tielgx has no fp!\n"); abort(); return 0; } static inline int dwarf_get (struct dwarf_cursor *c, dwarf_loc_t loc, unw_word_t *val) { if (!DWARF_GET_LOC (loc)) return -1; *val = *(tilegx_reg_t *) (intptr_t) DWARF_GET_LOC (loc); return 0; } static inline int dwarf_put (struct dwarf_cursor *c, dwarf_loc_t loc, unw_word_t val) { if (!DWARF_GET_LOC (loc)) return -1; *(tilegx_reg_t *) (intptr_t) DWARF_GET_LOC (loc) = val; return 0; } #else /* !UNW_LOCAL_ONLY */ #define DWARF_LOC_TYPE_FP (1 << 0) #define DWARF_LOC_TYPE_REG (1 << 1) #define DWARF_NULL_LOC DWARF_LOC (0, 0) #define DWARF_IS_NULL_LOC(l) \ ({ dwarf_loc_t _l = (l); _l.val == 0 && _l.type == 0; }) #define DWARF_LOC(r, t) ((dwarf_loc_t) { .val = (r), .type = (t) }) #define DWARF_IS_REG_LOC(l) (((l).type & DWARF_LOC_TYPE_REG) != 0) #define DWARF_IS_FP_LOC(l) (((l).type & DWARF_LOC_TYPE_FP) != 0) #define DWARF_REG_LOC(c,r) DWARF_LOC((r), DWARF_LOC_TYPE_REG) #define DWARF_MEM_LOC(c,m) DWARF_LOC ((m), 0) #define DWARF_FPREG_LOC(c,r) DWARF_LOC((r), (DWARF_LOC_TYPE_REG \ | DWARF_LOC_TYPE_FP)) /* TILEGX has no fp. */ static inline int dwarf_getfp (struct dwarf_cursor *c, dwarf_loc_t loc, unw_fpreg_t *val) { Debug (1, "Tielgx has no fp!\n"); abort(); return 0; } static inline int dwarf_putfp (struct dwarf_cursor *c, dwarf_loc_t loc, unw_fpreg_t val) { Debug (1, "Tielgx has no fp!\n"); abort(); return 0; } static inline int dwarf_get (struct dwarf_cursor *c, dwarf_loc_t loc, unw_word_t *val) { if (DWARF_IS_NULL_LOC (loc)) return -UNW_EBADREG; /* If a code-generator were to save a value of type unw_word_t in a floating-point register, we would have to support this case. I suppose it could happen with MMX registers, but does it really happen? */ assert (!DWARF_IS_FP_LOC (loc)); if (DWARF_IS_REG_LOC (loc)) return (*c->as->acc.access_reg) (c->as, DWARF_GET_LOC (loc), val, 0, c->as_arg); return (*c->as->acc.access_mem) (c->as, DWARF_GET_LOC (loc), val, 0, c->as_arg); } static inline int dwarf_put (struct dwarf_cursor *c, dwarf_loc_t loc, unw_word_t val) { if (DWARF_IS_NULL_LOC (loc)) return -UNW_EBADREG; /* If a code-generator were to save a value of type unw_word_t in a floating-point register, we would have to support this case. I suppose it could happen with MMX registers, but does it really happen? */ assert (!DWARF_IS_FP_LOC (loc)); if (DWARF_IS_REG_LOC (loc)) return (*c->as->acc.access_reg) (c->as, DWARF_GET_LOC (loc), &val, 1, c->as_arg); return (*c->as->acc.access_mem) (c->as, DWARF_GET_LOC (loc), &val, 1, c->as_arg); } #endif /* !UNW_LOCAL_ONLY */ #define tdep_getcontext_trace unw_getcontext #define tdep_init_done UNW_OBJ(init_done) #define tdep_needs_initialization UNW_OBJ(needs_initialization) #define tdep_init UNW_OBJ(init) /* Platforms that support UNW_INFO_FORMAT_TABLE need to define tdep_search_unwind_table. */ #define tdep_search_unwind_table dwarf_search_unwind_table #define tdep_find_unwind_table dwarf_find_unwind_table #define tdep_uc_addr UNW_ARCH_OBJ(uc_addr) #define tdep_get_elf_image UNW_ARCH_OBJ(get_elf_image) #define tdep_get_exe_image_path UNW_ARCH_OBJ(get_exe_image_path) #define tdep_access_reg UNW_OBJ(access_reg) #define tdep_access_fpreg UNW_OBJ(access_fpreg) #define tdep_fetch_frame(c,ip,n) do {} while(0) #define tdep_cache_frame(c) 0 #define tdep_reuse_frame(c,frame) do {} while(0) #define tdep_stash_frame(c,rs) do {} while(0) #define tdep_trace(cur,addr,n) (-UNW_ENOINFO) #ifdef UNW_LOCAL_ONLY #define tdep_find_proc_info(c,ip,n) \ dwarf_find_proc_info((c)->as, (ip), &(c)->pi, (n), \ (c)->as_arg) #define tdep_put_unwind_info(as,pi,arg) \ dwarf_put_unwind_info((as), (pi), (arg)) #else #define tdep_find_proc_info(c,ip,n) \ (*(c)->as->acc.find_proc_info)((c)->as, (ip), &(c)->pi, (n), \ (c)->as_arg) #define tdep_put_unwind_info(as,pi,arg) \ (*(as)->acc.put_unwind_info)((as), (pi), (arg)) #endif #define tdep_get_as(c) ((c)->dwarf.as) #define tdep_get_as_arg(c) ((c)->dwarf.as_arg) #define tdep_get_ip(c) ((c)->dwarf.ip) extern atomic_bool tdep_init_done; extern void tdep_init (void); extern int tdep_search_unwind_table (unw_addr_space_t as, unw_word_t ip, unw_dyn_info_t *di, unw_proc_info_t *pi, int need_unwind_info, void *arg); extern void *tdep_uc_addr (ucontext_t *uc, int reg); extern int tdep_get_elf_image (struct elf_image *ei, pid_t pid, unw_word_t ip, unsigned long *segbase, unsigned long *mapoff, char *path, size_t pathlen); extern void tdep_get_exe_image_path (char *path); extern int tdep_access_reg (struct cursor *c, unw_regnum_t reg, unw_word_t *valp, int write); extern int tdep_access_fpreg (struct cursor *c, unw_regnum_t reg, unw_fpreg_t *valp, int write); #endif /* TILEGX_LIBUNWIND_I_H */
/* libunwind - a platform-independent unwind library Copyright (C) 2008 CodeSourcery Copyright (C) 2014 Tilera Corp. This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef TILEGX_LIBUNWIND_I_H #define TILEGX_LIBUNWIND_I_H /* Target-dependent definitions that are internal to libunwind but need to be shared with target-independent code. */ #include <stdlib.h> #include <libunwind.h> #include <stdatomic.h> # include "elf64.h" #include "mempool.h" #include "dwarf.h" typedef struct { /* no Tilegx-specific fast trace */ } unw_tdep_frame_t; struct unw_addr_space { struct unw_accessors acc; int big_endian; tilegx_abi_t abi; unsigned int addr_size; unw_caching_policy_t caching_policy; _Atomic uint32_t cache_generation; unw_word_t dyn_generation; /* see dyn-common.h */ unw_word_t dyn_info_list_addr; /* (cached) dyn_info_list_addr */ struct dwarf_rs_cache global_cache; struct unw_debug_frame_list *debug_frames; }; #define tdep_big_endian(as) ((as)->big_endian) struct cursor { struct dwarf_cursor dwarf; /* must be first */ unw_word_t sigcontext_addr; unw_word_t sigcontext_sp; unw_word_t sigcontext_pc; }; #define DWARF_GET_LOC(l) ((l).val) #ifndef UNW_REMOTE_ONLY typedef long tilegx_reg_t; #endif #ifdef UNW_LOCAL_ONLY #define DWARF_NULL_LOC DWARF_LOC (0, 0) #define DWARF_IS_NULL_LOC(l) (DWARF_GET_LOC (l) == 0) #define DWARF_LOC(r, t) ((dwarf_loc_t) { .val = (r) }) #define DWARF_IS_REG_LOC(l) 0 #define DWARF_REG_LOC(c,r) (DWARF_LOC((unw_word_t) (intptr_t) \ tdep_uc_addr((c)->as_arg, (r)), 0)) #define DWARF_MEM_LOC(c,m) DWARF_LOC ((m), 0) #define DWARF_FPREG_LOC(c,r) (DWARF_LOC((unw_word_t) (intptr_t) \ tdep_uc_addr((c)->as_arg, (r)), 0)) /* Tilegx has no FP. */ static inline int dwarf_getfp (struct dwarf_cursor *c, dwarf_loc_t loc, unw_fpreg_t *val) { Debug (1, "Tielgx has no fp!\n"); abort(); return 0; } static inline int dwarf_putfp (struct dwarf_cursor *c, dwarf_loc_t loc, unw_fpreg_t val) { Debug (1, "Tielgx has no fp!\n"); abort(); return 0; } static inline int dwarf_get (struct dwarf_cursor *c, dwarf_loc_t loc, unw_word_t *val) { if (!DWARF_GET_LOC (loc)) return -1; *val = *(tilegx_reg_t *) (intptr_t) DWARF_GET_LOC (loc); return 0; } static inline int dwarf_put (struct dwarf_cursor *c, dwarf_loc_t loc, unw_word_t val) { if (!DWARF_GET_LOC (loc)) return -1; *(tilegx_reg_t *) (intptr_t) DWARF_GET_LOC (loc) = val; return 0; } #else /* !UNW_LOCAL_ONLY */ #define DWARF_LOC_TYPE_FP (1 << 0) #define DWARF_LOC_TYPE_REG (1 << 1) #define DWARF_NULL_LOC DWARF_LOC (0, 0) #define DWARF_IS_NULL_LOC(l) \ ({ dwarf_loc_t _l = (l); _l.val == 0 && _l.type == 0; }) #define DWARF_LOC(r, t) ((dwarf_loc_t) { .val = (r), .type = (t) }) #define DWARF_IS_REG_LOC(l) (((l).type & DWARF_LOC_TYPE_REG) != 0) #define DWARF_IS_FP_LOC(l) (((l).type & DWARF_LOC_TYPE_FP) != 0) #define DWARF_REG_LOC(c,r) DWARF_LOC((r), DWARF_LOC_TYPE_REG) #define DWARF_MEM_LOC(c,m) DWARF_LOC ((m), 0) #define DWARF_FPREG_LOC(c,r) DWARF_LOC((r), (DWARF_LOC_TYPE_REG \ | DWARF_LOC_TYPE_FP)) /* TILEGX has no fp. */ static inline int dwarf_getfp (struct dwarf_cursor *c, dwarf_loc_t loc, unw_fpreg_t *val) { Debug (1, "Tielgx has no fp!\n"); abort(); return 0; } static inline int dwarf_putfp (struct dwarf_cursor *c, dwarf_loc_t loc, unw_fpreg_t val) { Debug (1, "Tielgx has no fp!\n"); abort(); return 0; } static inline int dwarf_get (struct dwarf_cursor *c, dwarf_loc_t loc, unw_word_t *val) { if (DWARF_IS_NULL_LOC (loc)) return -UNW_EBADREG; /* If a code-generator were to save a value of type unw_word_t in a floating-point register, we would have to support this case. I suppose it could happen with MMX registers, but does it really happen? */ assert (!DWARF_IS_FP_LOC (loc)); if (DWARF_IS_REG_LOC (loc)) return (*c->as->acc.access_reg) (c->as, DWARF_GET_LOC (loc), val, 0, c->as_arg); return (*c->as->acc.access_mem) (c->as, DWARF_GET_LOC (loc), val, 0, c->as_arg); } static inline int dwarf_put (struct dwarf_cursor *c, dwarf_loc_t loc, unw_word_t val) { if (DWARF_IS_NULL_LOC (loc)) return -UNW_EBADREG; /* If a code-generator were to save a value of type unw_word_t in a floating-point register, we would have to support this case. I suppose it could happen with MMX registers, but does it really happen? */ assert (!DWARF_IS_FP_LOC (loc)); if (DWARF_IS_REG_LOC (loc)) return (*c->as->acc.access_reg) (c->as, DWARF_GET_LOC (loc), &val, 1, c->as_arg); return (*c->as->acc.access_mem) (c->as, DWARF_GET_LOC (loc), &val, 1, c->as_arg); } #endif /* !UNW_LOCAL_ONLY */ #define tdep_getcontext_trace unw_getcontext #define tdep_init_done UNW_OBJ(init_done) #define tdep_needs_initialization UNW_OBJ(needs_initialization) #define tdep_init UNW_OBJ(init) /* Platforms that support UNW_INFO_FORMAT_TABLE need to define tdep_search_unwind_table. */ #define tdep_search_unwind_table dwarf_search_unwind_table #define tdep_find_unwind_table dwarf_find_unwind_table #define tdep_uc_addr UNW_ARCH_OBJ(uc_addr) #define tdep_get_elf_image UNW_ARCH_OBJ(get_elf_image) #define tdep_get_exe_image_path UNW_ARCH_OBJ(get_exe_image_path) #define tdep_access_reg UNW_OBJ(access_reg) #define tdep_access_fpreg UNW_OBJ(access_fpreg) #define tdep_fetch_frame(c,ip,n) do {} while(0) #define tdep_cache_frame(c) 0 #define tdep_reuse_frame(c,frame) do {} while(0) #define tdep_stash_frame(c,rs) do {} while(0) #define tdep_trace(cur,addr,n) (-UNW_ENOINFO) #ifdef UNW_LOCAL_ONLY #define tdep_find_proc_info(c,ip,n) \ dwarf_find_proc_info((c)->as, (ip), &(c)->pi, (n), \ (c)->as_arg) #define tdep_put_unwind_info(as,pi,arg) \ dwarf_put_unwind_info((as), (pi), (arg)) #else #define tdep_find_proc_info(c,ip,n) \ (*(c)->as->acc.find_proc_info)((c)->as, (ip), &(c)->pi, (n), \ (c)->as_arg) #define tdep_put_unwind_info(as,pi,arg) \ (*(as)->acc.put_unwind_info)((as), (pi), (arg)) #endif #define tdep_get_as(c) ((c)->dwarf.as) #define tdep_get_as_arg(c) ((c)->dwarf.as_arg) #define tdep_get_ip(c) ((c)->dwarf.ip) extern atomic_bool tdep_init_done; extern void tdep_init (void); extern int tdep_search_unwind_table (unw_addr_space_t as, unw_word_t ip, unw_dyn_info_t *di, unw_proc_info_t *pi, int need_unwind_info, void *arg); extern void *tdep_uc_addr (ucontext_t *uc, int reg); extern int tdep_get_elf_image (struct elf_image *ei, pid_t pid, unw_word_t ip, unsigned long *segbase, unsigned long *mapoff, char *path, size_t pathlen); extern void tdep_get_exe_image_path (char *path); extern int tdep_access_reg (struct cursor *c, unw_regnum_t reg, unw_word_t *valp, int write); extern int tdep_access_fpreg (struct cursor *c, unw_regnum_t reg, unw_fpreg_t *valp, int write); #endif /* TILEGX_LIBUNWIND_I_H */
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/pal/src/libunwind/src/ia64/Lregs.c
#define UNW_LOCAL_ONLY #include <libunwind.h> #if defined(UNW_LOCAL_ONLY) && !defined(UNW_REMOTE_ONLY) #include "Gregs.c" #endif
#define UNW_LOCAL_ONLY #include <libunwind.h> #if defined(UNW_LOCAL_ONLY) && !defined(UNW_REMOTE_ONLY) #include "Gregs.c" #endif
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/pal/src/libunwind/src/tilegx/Lcreate_addr_space.c
#define UNW_LOCAL_ONLY #include <libunwind.h> #if defined(UNW_LOCAL_ONLY) && !defined(UNW_REMOTE_ONLY) #include "Gcreate_addr_space.c" #endif
#define UNW_LOCAL_ONLY #include <libunwind.h> #if defined(UNW_LOCAL_ONLY) && !defined(UNW_REMOTE_ONLY) #include "Gcreate_addr_space.c" #endif
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/pal/src/include/pal/utf8.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*++ Module Name: include/pal/utf8.h Abstract: Header file for UTF-8 conversion functions. Revision History: --*/ #ifndef _PAL_UTF8_H_ #define _PAL_UTF8_H_ #include <pal/palinternal.h> /* for WCHAR */ #ifdef __cplusplus extern "C" { #endif // __cplusplus /*++ Function : UTF8ToUnicode Convert a string from UTF-8 to UTF-16 (UCS-2) --*/ int UTF8ToUnicode(LPCSTR lpSrcStr, int cchSrc, LPWSTR lpDestStr, int cchDest, DWORD dwFlags); /*++ Function : UnicodeToUTF8 Convert a string from UTF-16 (UCS-2) to UTF-8 --*/ int UnicodeToUTF8(LPCWSTR lpSrcStr, int cchSrc, LPSTR lpDestStr, int cchDest); #ifdef __cplusplus } #endif // __cplusplus #endif /* _PAL_UTF8_H_ */
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*++ Module Name: include/pal/utf8.h Abstract: Header file for UTF-8 conversion functions. Revision History: --*/ #ifndef _PAL_UTF8_H_ #define _PAL_UTF8_H_ #include <pal/palinternal.h> /* for WCHAR */ #ifdef __cplusplus extern "C" { #endif // __cplusplus /*++ Function : UTF8ToUnicode Convert a string from UTF-8 to UTF-16 (UCS-2) --*/ int UTF8ToUnicode(LPCSTR lpSrcStr, int cchSrc, LPWSTR lpDestStr, int cchDest, DWORD dwFlags); /*++ Function : UnicodeToUTF8 Convert a string from UTF-16 (UCS-2) to UTF-8 --*/ int UnicodeToUTF8(LPCWSTR lpSrcStr, int cchSrc, LPSTR lpDestStr, int cchDest); #ifdef __cplusplus } #endif // __cplusplus #endif /* _PAL_UTF8_H_ */
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/mono/mono/sgen/sgen-debug.c
/** * \file * Collector debugging * * Author: * Paolo Molaro ([email protected]) * Rodrigo Kumpera ([email protected]) * * Copyright 2005-2011 Novell, Inc (http://www.novell.com) * Copyright 2011 Xamarin Inc (http://www.xamarin.com) * Copyright 2011 Xamarin, Inc. * Copyright (C) 2012 Xamarin Inc * * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #include "config.h" #ifdef HAVE_SGEN_GC #include <string.h> #include "mono/sgen/sgen-gc.h" #include "mono/sgen/sgen-cardtable.h" #include "mono/sgen/sgen-protocol.h" #include "mono/sgen/sgen-memory-governor.h" #include "mono/sgen/sgen-pinning.h" #include "mono/sgen/sgen-client.h" #if _MSC_VER #pragma warning(disable:4312) // FIXME pointer cast to different size #endif #ifndef DISABLE_SGEN_DEBUG_HELPERS #define LOAD_VTABLE SGEN_LOAD_VTABLE #define object_is_forwarded SGEN_OBJECT_IS_FORWARDED #define object_is_pinned SGEN_OBJECT_IS_PINNED #define safe_object_get_size sgen_safe_object_get_size void sgen_describe_ptr (char *ptr); void sgen_check_object (GCObject *obj); /* * ###################################################################### * ######## Collector debugging * ###################################################################### */ static const char*descriptor_types [] = { "INVALID", "run length", "bitmap", "small pointer-free", "complex", "vector", "complex arrray", "complex pointer-free" }; static char* describe_nursery_ptr (char *ptr, gboolean need_setup); static void describe_pointer (char *ptr, gboolean need_setup) { GCVTable vtable; SgenDescriptor desc; int type; char *start; char *forwarded; mword size; restart: if (sgen_ptr_in_nursery (ptr)) { start = describe_nursery_ptr (ptr, need_setup); if (!start) return; ptr = start; vtable = LOAD_VTABLE ((GCObject*)ptr); } else { if (sgen_ptr_is_in_los (ptr, &start)) { if (ptr == start) printf ("Pointer is the start of object %p in LOS space.\n", start); else printf ("Pointer is at offset 0x%x of object %p in LOS space.\n", (int)(ptr - start), start); ptr = start; mono_sgen_los_describe_pointer (ptr); vtable = LOAD_VTABLE ((GCObject*)ptr); } else if (sgen_major_collector.ptr_is_in_non_pinned_space (ptr, &start)) { if (ptr == start) printf ("Pointer is the start of object %p in oldspace.\n", start); else if (start) printf ("Pointer is at offset 0x%x of object %p in oldspace.\n", (int)(ptr - start), start); else printf ("Pointer inside oldspace.\n"); if (start) ptr = start; vtable = (GCVTable)sgen_major_collector.describe_pointer (ptr); } else if (sgen_major_collector.ptr_is_from_pinned_alloc (ptr)) { // FIXME: Handle pointers to the inside of objects printf ("Pointer is inside a pinned chunk.\n"); vtable = LOAD_VTABLE ((GCObject*)ptr); } else { printf ("Pointer unknown.\n"); return; } } if (object_is_pinned (ptr)) printf ("Object is pinned.\n"); if ((forwarded = (char *)object_is_forwarded (ptr))) { printf ("Object is forwarded to %p:\n", forwarded); ptr = forwarded; goto restart; } printf ("VTable: %p\n", vtable); if (vtable == NULL) { printf ("VTable is invalid (empty).\n"); goto invalid_vtable; } if (sgen_ptr_in_nursery (vtable)) { printf ("VTable is invalid (points inside nursery).\n"); goto invalid_vtable; } printf ("Class: %s.%s\n", sgen_client_vtable_get_namespace (vtable), sgen_client_vtable_get_name (vtable)); desc = sgen_vtable_get_descriptor (vtable); printf ("Descriptor: %lx\n", (long)desc); type = desc & DESC_TYPE_MASK; printf ("Descriptor type: %d (%s)\n", type, descriptor_types [type]); size = sgen_safe_object_get_size ((GCObject*)ptr); printf ("Size: %d\n", (int)size); invalid_vtable: ; sgen_client_describe_invalid_pointer ((GCObject *) ptr); } void sgen_describe_ptr (char *ptr) { describe_pointer (ptr, TRUE); } static gboolean missing_remsets; /* * We let a missing remset slide if the target object is pinned, * because the store might have happened but the remset not yet added, * but in that case the target must be pinned. We might theoretically * miss some missing remsets this way, but it's very unlikely. */ #undef HANDLE_PTR #define HANDLE_PTR(ptr,obj) do { \ if (*(ptr) && sgen_ptr_in_nursery ((char*)*(ptr))) { \ if (!sgen_get_remset ()->find_address ((char*)(ptr)) && !sgen_cement_lookup (*(ptr))) { \ GCVTable __vt = SGEN_LOAD_VTABLE (obj); \ gboolean is_pinned = object_is_pinned (*(ptr)); \ SGEN_LOG (0, "Oldspace->newspace reference %p at offset %ld in object %p (%s.%s) not found in remsets%s.", *(ptr), (long)((char*)(ptr) - (char*)(obj)), (obj), sgen_client_vtable_get_namespace (__vt), sgen_client_vtable_get_name (__vt), is_pinned ? ", but object is pinned" : ""); \ sgen_binary_protocol_missing_remset ((obj), __vt, (int) ((char*)(ptr) - (char*)(obj)), *(ptr), (gpointer)LOAD_VTABLE(*(ptr)), is_pinned); \ if (!is_pinned) \ missing_remsets = TRUE; \ } \ } \ } while (0) /* * Check that each object reference which points into the nursery can * be found in the remembered sets. */ static void check_consistency_callback (GCObject *obj, size_t size, void *dummy) { char *start = (char*)obj; GCVTable vt = LOAD_VTABLE (obj); SgenDescriptor desc = sgen_vtable_get_descriptor (vt); SGEN_LOG (8, "Scanning object %p, vtable: %p (%s)", start, vt, sgen_client_vtable_get_name (vt)); #include "sgen-scan-object.h" } /* * Perform consistency check of the heap. * * Assumes the world is stopped. */ void sgen_check_remset_consistency (void) { // Need to add more checks missing_remsets = FALSE; SGEN_LOG (1, "Begin heap consistency check..."); // Check that oldspace->newspace pointers are registered with the collector sgen_major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_ALL, (IterateObjectCallbackFunc)check_consistency_callback, NULL); sgen_los_iterate_objects ((IterateObjectCallbackFunc)check_consistency_callback, NULL); SGEN_LOG (1, "Heap consistency check done."); if (missing_remsets) sgen_binary_protocol_flush_buffers (TRUE); if (!sgen_binary_protocol_is_enabled ()) g_assert (!missing_remsets); } static gboolean is_major_or_los_object_marked (GCObject *obj) { if (sgen_safe_object_get_size ((GCObject*)obj) > SGEN_MAX_SMALL_OBJ_SIZE) { return sgen_los_object_is_pinned (obj); } else { return sgen_get_major_collector ()->is_object_live (obj); } } #undef HANDLE_PTR #define HANDLE_PTR(ptr,obj) do { \ if (*(ptr) && !sgen_ptr_in_nursery ((char*)*(ptr)) && !is_major_or_los_object_marked ((GCObject*)*(ptr))) { \ if (!cards || !sgen_get_remset ()->find_address_with_cards (start, cards, (char*)(ptr))) { \ GCVTable __vt = SGEN_LOAD_VTABLE (obj); \ SGEN_LOG (0, "major->major reference %p at offset %ld in object %p (%s.%s) not found in remsets.", *(ptr), (long)((char*)(ptr) - (char*)(obj)), (obj), sgen_client_vtable_get_namespace (__vt), sgen_client_vtable_get_name (__vt)); \ sgen_binary_protocol_missing_remset ((obj), __vt, (int) ((char*)(ptr) - (char*)(obj)), *(ptr), (gpointer)LOAD_VTABLE(*(ptr)), object_is_pinned (*(ptr))); \ missing_remsets = TRUE; \ } \ } \ } while (0) static void check_mod_union_callback (GCObject *obj, size_t size, void *dummy) { char *start = (char*)obj; gboolean in_los = (gboolean) (size_t) dummy; GCVTable vt = LOAD_VTABLE (obj); SgenDescriptor desc = sgen_vtable_get_descriptor (vt); guint8 *cards; SGEN_LOG (8, "Scanning object %p, vtable: %p (%s)", obj, vt, sgen_client_vtable_get_name (vt)); if (!is_major_or_los_object_marked (obj)) return; if (in_los) cards = sgen_los_header_for_object (obj)->cardtable_mod_union; else cards = sgen_get_major_collector ()->get_cardtable_mod_union_for_reference (start); #include "sgen-scan-object.h" } void sgen_check_mod_union_consistency (void) { missing_remsets = FALSE; sgen_major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_ALL, (IterateObjectCallbackFunc)check_mod_union_callback, (void*)FALSE); sgen_los_iterate_objects ((IterateObjectCallbackFunc)check_mod_union_callback, (void*)TRUE); if (!sgen_binary_protocol_is_enabled ()) g_assert (!missing_remsets); } #undef HANDLE_PTR #define HANDLE_PTR(ptr,obj) do { \ if (*(ptr) && !LOAD_VTABLE (*(ptr))) \ g_error ("Could not load vtable for obj %p slot %ld (size %ld)", obj, (long)((char*)ptr - (char*)obj), (long)safe_object_get_size ((GCObject*)obj)); \ } while (0) static void check_major_refs_callback (GCObject *obj, size_t size, void *dummy) { char *start = (char*)obj; SgenDescriptor desc = sgen_obj_get_descriptor (obj); #include "sgen-scan-object.h" } void sgen_check_major_refs (void) { sgen_major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_ALL, (IterateObjectCallbackFunc)check_major_refs_callback, NULL); sgen_los_iterate_objects ((IterateObjectCallbackFunc)check_major_refs_callback, NULL); } /* Check that the reference is valid */ #undef HANDLE_PTR #define HANDLE_PTR(ptr,obj) do { \ if (*(ptr)) { \ g_assert (sgen_client_vtable_get_namespace (SGEN_LOAD_VTABLE_UNCHECKED (*(ptr)))); \ } \ } while (0) /* * sgen_check_object: * * Perform consistency check on an object. Currently we only check that the * reference fields are valid. */ void sgen_check_object (GCObject *obj) { char *start = (char*)obj; SgenDescriptor desc; if (!start) return; desc = sgen_obj_get_descriptor (obj); #include "sgen-scan-object.h" } static GCObject **valid_nursery_objects; static int valid_nursery_object_count; static gboolean broken_heap; static void setup_mono_sgen_scan_area_with_callback (GCObject *object, size_t size, void *data) { valid_nursery_objects [valid_nursery_object_count++] = object; } static void setup_valid_nursery_objects (void) { if (!valid_nursery_objects) valid_nursery_objects = (GCObject **)sgen_alloc_os_memory (sgen_nursery_max_size, (SgenAllocFlags)(SGEN_ALLOC_INTERNAL | SGEN_ALLOC_ACTIVATE), "debugging data", MONO_MEM_ACCOUNT_SGEN_DEBUGGING); valid_nursery_object_count = 0; sgen_scan_area_with_callback (sgen_nursery_section->data, sgen_nursery_section->end_data, setup_mono_sgen_scan_area_with_callback, NULL, FALSE, FALSE); } static gboolean find_object_in_nursery_dump (char *object) { int first = 0, last = valid_nursery_object_count; while (first < last) { int middle = first + ((last - first) >> 1); if (object == (char*)valid_nursery_objects [middle]) return TRUE; if (object < (char*)valid_nursery_objects [middle]) last = middle; else first = middle + 1; } g_assert (first == last); return FALSE; } static void iterate_valid_nursery_objects (IterateObjectCallbackFunc callback, void *data) { int i; for (i = 0; i < valid_nursery_object_count; ++i) { GCObject *obj = valid_nursery_objects [i]; callback (obj, safe_object_get_size (obj), data); } } static char* describe_nursery_ptr (char *ptr, gboolean need_setup) { int i; if (need_setup) setup_valid_nursery_objects (); for (i = 0; i < valid_nursery_object_count - 1; ++i) { if ((char*)valid_nursery_objects [i + 1] > ptr) break; } if (i >= valid_nursery_object_count || (char*)valid_nursery_objects [i] + safe_object_get_size (valid_nursery_objects [i]) < ptr) { SGEN_LOG (0, "nursery-ptr (unalloc'd-memory)"); return NULL; } else { GCObject *obj = valid_nursery_objects [i]; if ((char*)obj == ptr) SGEN_LOG (0, "nursery-ptr %p", obj); else SGEN_LOG (0, "nursery-ptr %p (interior-ptr offset %ld)", obj, (long)(ptr - (char*)obj)); return (char*)obj; } } static gboolean is_valid_object_pointer (char *object) { if (sgen_ptr_in_nursery (object)) return find_object_in_nursery_dump (object); if (sgen_los_is_valid_object (object)) return TRUE; if (sgen_major_collector.is_valid_object (object)) return TRUE; return FALSE; } static void bad_pointer_spew (char *obj, char **slot) { char *ptr = *slot; GCVTable vtable = LOAD_VTABLE ((GCObject*)obj); SGEN_LOG (0, "Invalid object pointer %p at offset %ld in object %p (%s.%s):", ptr, (long)((char*)slot - obj), obj, sgen_client_vtable_get_namespace (vtable), sgen_client_vtable_get_name (vtable)); describe_pointer (ptr, FALSE); broken_heap = TRUE; } static void missing_remset_spew (char *obj, char **slot) { char *ptr = *slot; GCVTable vtable = LOAD_VTABLE ((GCObject*)obj); SGEN_LOG (0, "Oldspace->newspace reference %p at offset %ld in object %p (%s.%s) not found in remsets.", ptr, (long)((char*)slot - obj), obj, sgen_client_vtable_get_namespace (vtable), sgen_client_vtable_get_name (vtable)); broken_heap = TRUE; } /* FIXME Flag missing remsets due to pinning as non fatal */ #undef HANDLE_PTR #define HANDLE_PTR(ptr,obj) do { \ if (*(char**)ptr) { \ if (!is_valid_object_pointer (*(char**)ptr)) { \ bad_pointer_spew ((char*)obj, (char**)ptr); \ } else if (!sgen_ptr_in_nursery (obj) && sgen_ptr_in_nursery ((char*)*ptr)) { \ if (!allow_missing_pinned && !SGEN_OBJECT_IS_PINNED (*(ptr)) && !sgen_get_remset ()->find_address ((char*)(ptr)) && !sgen_cement_lookup (*(ptr))) \ missing_remset_spew ((char*)obj, (char**)ptr); \ } \ } \ } while (0) static void verify_object_pointers_callback (GCObject *obj, size_t size, void *data) { char *start = (char*)obj; gboolean allow_missing_pinned = (gboolean) (size_t) data; SgenDescriptor desc = sgen_obj_get_descriptor_safe (obj); #include "sgen-scan-object.h" } /* FIXME: -This heap checker is racy regarding inlined write barriers and other JIT tricks that depend on OP_DUMMY_USE. */ void sgen_check_whole_heap (gboolean allow_missing_pinned) { setup_valid_nursery_objects (); broken_heap = FALSE; sgen_scan_area_with_callback (sgen_nursery_section->data, sgen_nursery_section->end_data, verify_object_pointers_callback, (void*) (size_t) allow_missing_pinned, FALSE, TRUE); sgen_major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_ALL, verify_object_pointers_callback, (void*) (size_t) allow_missing_pinned); sgen_los_iterate_objects (verify_object_pointers_callback, (void*) (size_t) allow_missing_pinned); g_assert (!broken_heap); } static gboolean ptr_in_heap (char *object) { if (sgen_ptr_in_nursery (object)) return TRUE; if (sgen_los_is_valid_object (object)) return TRUE; if (sgen_major_collector.is_valid_object (object)) return TRUE; return FALSE; } /* * sgen_check_objref: * Do consistency checks on the object reference OBJ. Assert on failure. */ void sgen_check_objref (char *obj) { g_assert (ptr_in_heap (obj)); } static void find_pinning_ref_from_thread (char *obj, size_t size) { #ifndef SGEN_WITHOUT_MONO char *endobj = obj + size; FOREACH_THREAD_EXCLUDE (info, MONO_THREAD_INFO_FLAGS_NO_GC) { mword *ctxstart, *ctxcurrent, *ctxend; char **start = (char**)info->client_info.stack_start; if (info->client_info.skip) continue; while (start < (char**)info->client_info.info.stack_end) { if (*start >= obj && *start < endobj) SGEN_LOG (0, "Object %p referenced in thread %p (id %p) at %p, stack: %p-%p", obj, info, (gpointer)(gsize) mono_thread_info_get_tid (info), start, info->client_info.stack_start, info->client_info.info.stack_end); start++; } for (ctxstart = ctxcurrent = (mword*) &info->client_info.ctx, ctxend = (mword*) (&info->client_info.ctx + 1); ctxcurrent < ctxend; ctxcurrent ++) { mword w = *ctxcurrent; if (w >= (mword)obj && w < (mword)obj + size) SGEN_LOG (0, "Object %p referenced in saved reg %d of thread %p (id %p)", obj, (int) (ctxcurrent - ctxstart), info, (gpointer)(gsize) mono_thread_info_get_tid (info)); } } FOREACH_THREAD_END #endif } /* * Debugging function: find in the conservative roots where @obj is being pinned. */ static G_GNUC_UNUSED void find_pinning_reference (char *obj, size_t size) { char **start; RootRecord *root; char *endobj = obj + size; SGEN_HASH_TABLE_FOREACH (&sgen_roots_hash [ROOT_TYPE_NORMAL], char **, start, RootRecord *, root) { /* if desc is non-null it has precise info */ if (!root->root_desc) { while (start < (char**)root->end_root) { if (*start >= obj && *start < endobj) { SGEN_LOG (0, "Object %p referenced in pinned roots %p-%p\n", obj, start, root->end_root); } start++; } } } SGEN_HASH_TABLE_FOREACH_END; find_pinning_ref_from_thread (obj, size); } #undef HANDLE_PTR #define HANDLE_PTR(ptr,obj) do { \ char* __target = *(char**)ptr; \ if (__target) { \ if (sgen_ptr_in_nursery (__target)) { \ g_assert (!SGEN_OBJECT_IS_FORWARDED (__target)); \ } else { \ mword __size = sgen_safe_object_get_size ((GCObject*)__target); \ if (__size <= SGEN_MAX_SMALL_OBJ_SIZE) \ g_assert (sgen_major_collector.is_object_live ((GCObject*)__target)); \ else \ g_assert (sgen_los_object_is_pinned ((GCObject*)__target)); \ } \ } \ } while (0) static void check_marked_callback (GCObject *obj, size_t size, void *dummy) { char *start = (char*)obj; gboolean flag = (gboolean) (size_t) dummy; SgenDescriptor desc; if (sgen_ptr_in_nursery (start)) { if (flag) SGEN_ASSERT (0, SGEN_OBJECT_IS_PINNED (obj), "All objects remaining in the nursery must be pinned"); } else if (flag) { if (!sgen_los_object_is_pinned (obj)) return; } else { if (!sgen_major_collector.is_object_live (obj)) return; } desc = sgen_obj_get_descriptor_safe (obj); #include "sgen-scan-object.h" } void sgen_check_heap_marked (gboolean nursery_must_be_pinned) { setup_valid_nursery_objects (); iterate_valid_nursery_objects (check_marked_callback, (void*)(size_t)nursery_must_be_pinned); sgen_major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_ALL, check_marked_callback, (void*)FALSE); sgen_los_iterate_objects (check_marked_callback, (void*)TRUE); } static void check_nursery_objects_untag_callback (char *obj, size_t size, void *data) { g_assert (!SGEN_OBJECT_IS_FORWARDED (obj)); g_assert (!SGEN_OBJECT_IS_PINNED (obj)); } void sgen_check_nursery_objects_untag (void) { sgen_clear_nursery_fragments (); sgen_scan_area_with_callback (sgen_nursery_section->data, sgen_nursery_section->end_data, (IterateObjectCallbackFunc)check_nursery_objects_untag_callback, NULL, FALSE, TRUE); } static void verify_scan_starts (char *start, char *end) { size_t i; for (i = 0; i < sgen_nursery_section->num_scan_start; ++i) { char *addr = sgen_nursery_section->scan_starts [i]; if (addr > start && addr < end) SGEN_LOG (0, "NFC-BAD SCAN START [%lu] %p for obj [%p %p]", (unsigned long)i, addr, start, end); } } void sgen_debug_verify_nursery (gboolean do_dump_nursery_content) { char *start, *end, *cur, *hole_start; if (sgen_nursery_canaries_enabled ()) SGEN_LOG (0, "Checking nursery canaries..."); /*This cleans up unused fragments */ sgen_nursery_allocator_prepare_for_pinning (); hole_start = start = cur = sgen_get_nursery_start (); end = sgen_get_nursery_end (); while (cur < end) { size_t ss, size; gboolean is_array_fill; if (!*(void**)cur) { cur += sizeof (void*); continue; } if (object_is_forwarded (cur)) SGEN_LOG (0, "FORWARDED OBJ %p", cur); else if (object_is_pinned (cur)) SGEN_LOG (0, "PINNED OBJ %p", cur); ss = safe_object_get_size ((GCObject*)cur); size = SGEN_ALIGN_UP (ss); verify_scan_starts (cur, cur + size); is_array_fill = sgen_client_object_is_array_fill ((GCObject*)cur); if (do_dump_nursery_content) { GCVTable vtable = SGEN_LOAD_VTABLE ((GCObject*)cur); if (cur > hole_start) SGEN_LOG (0, "HOLE [%p %p %d]", hole_start, cur, (int)(cur - hole_start)); SGEN_LOG (0, "OBJ [%p %p %d %d %s.%s %d]", cur, cur + size, (int)size, (int)ss, sgen_client_vtable_get_namespace (vtable), sgen_client_vtable_get_name (vtable), is_array_fill); } if (sgen_nursery_canaries_enabled () && !is_array_fill) { CHECK_CANARY_FOR_OBJECT ((GCObject*)cur, TRUE); CANARIFY_SIZE (size); } cur += size; hole_start = cur; } } /* * Checks that no objects in the nursery are fowarded or pinned. This * is a precondition to restarting the mutator while doing a * concurrent collection. Note that we don't clear fragments because * we depend on that having happened earlier. */ void sgen_debug_check_nursery_is_clean (void) { char *end, *cur; cur = sgen_get_nursery_start (); end = sgen_get_nursery_end (); while (cur < end) { size_t size; if (!*(void**)cur) { cur += sizeof (void*); continue; } g_assert (!object_is_forwarded (cur)); g_assert (!object_is_pinned (cur)); size = SGEN_ALIGN_UP (safe_object_get_size ((GCObject*)cur)); verify_scan_starts (cur, cur + size); cur += size; } } static gboolean scan_object_for_specific_ref_precise = TRUE; #undef HANDLE_PTR #define HANDLE_PTR(ptr,obj) do { \ if ((GCObject*)*(ptr) == key) { \ GCVTable vtable = SGEN_LOAD_VTABLE (*(ptr)); \ g_print ("found ref to %p in object %p (%s.%s) at offset %ld\n", \ key, (obj), sgen_client_vtable_get_namespace (vtable), sgen_client_vtable_get_name (vtable), (long)(((char*)(ptr) - (char*)(obj)))); \ } \ } while (0) static void scan_object_for_specific_ref (GCObject *obj, GCObject *key) { GCObject *forwarded; if ((forwarded = SGEN_OBJECT_IS_FORWARDED (obj))) obj = forwarded; if (scan_object_for_specific_ref_precise) { char *start = (char*)obj; SgenDescriptor desc = sgen_obj_get_descriptor_safe (obj); #include "sgen-scan-object.h" } else { mword *words = (mword*)obj; size_t size = safe_object_get_size (obj); int i; for (i = 0; i < size / sizeof (mword); ++i) { if (words [i] == (mword)key) { GCVTable vtable = SGEN_LOAD_VTABLE (obj); g_print ("found possible ref to %p in object %p (%s.%s) at offset %ld\n", key, obj, sgen_client_vtable_get_namespace (vtable), sgen_client_vtable_get_name (vtable), (long)(i * sizeof (mword))); } } } } static void scan_object_for_specific_ref_callback (GCObject *obj, size_t size, GCObject *key) { scan_object_for_specific_ref (obj, key); } static void check_root_obj_specific_ref (RootRecord *root, GCObject *key, GCObject *obj) { if (key != obj) return; g_print ("found ref to %p in root record %p\n", key, root); } static GCObject *check_key = NULL; static RootRecord *check_root = NULL; static void check_root_obj_specific_ref_from_marker (GCObject **obj, void *gc_data) { check_root_obj_specific_ref (check_root, check_key, *obj); } static void scan_roots_for_specific_ref (GCObject *key, int root_type) { void **start_root; RootRecord *root; check_key = key; SGEN_HASH_TABLE_FOREACH (&sgen_roots_hash [root_type], void **, start_root, RootRecord *, root) { SgenDescriptor desc = root->root_desc; check_root = root; switch (desc & ROOT_DESC_TYPE_MASK) { case ROOT_DESC_BITMAP: desc >>= ROOT_DESC_TYPE_SHIFT; while (desc) { if (desc & 1) check_root_obj_specific_ref (root, key, (GCObject *)*start_root); desc >>= 1; start_root++; } return; case ROOT_DESC_COMPLEX: { gsize *bitmap_data = (gsize *)sgen_get_complex_descriptor_bitmap (desc); int bwords = (int) ((*bitmap_data) - 1); void **start_run = start_root; bitmap_data++; while (bwords-- > 0) { gsize bmap = *bitmap_data++; void **objptr = start_run; while (bmap) { if (bmap & 1) check_root_obj_specific_ref (root, key, (GCObject *)*objptr); bmap >>= 1; ++objptr; } start_run += GC_BITS_PER_WORD; } break; } case ROOT_DESC_VECTOR: { void **p; for (p = start_root; p < (void**)root->end_root; p++) { if (*p) check_root_obj_specific_ref (root, key, (GCObject *)*p); } break; } case ROOT_DESC_USER: { SgenUserRootMarkFunc marker = sgen_get_user_descriptor_func (desc); marker (start_root, check_root_obj_specific_ref_from_marker, NULL); break; } case ROOT_DESC_RUN_LEN: g_assert_not_reached (); default: g_assert_not_reached (); } } SGEN_HASH_TABLE_FOREACH_END; check_key = NULL; check_root = NULL; } void mono_gc_scan_for_specific_ref (GCObject *key, gboolean precise) { void **ptr; RootRecord *root; scan_object_for_specific_ref_precise = precise; sgen_scan_area_with_callback (sgen_nursery_section->data, sgen_nursery_section->end_data, (IterateObjectCallbackFunc)scan_object_for_specific_ref_callback, key, TRUE, FALSE); sgen_major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_ALL, (IterateObjectCallbackFunc)scan_object_for_specific_ref_callback, key); sgen_los_iterate_objects ((IterateObjectCallbackFunc)scan_object_for_specific_ref_callback, key); scan_roots_for_specific_ref (key, ROOT_TYPE_NORMAL); scan_roots_for_specific_ref (key, ROOT_TYPE_WBARRIER); SGEN_HASH_TABLE_FOREACH (&sgen_roots_hash [ROOT_TYPE_PINNED], void **, ptr, RootRecord *, root) { while (ptr < (void**)root->end_root) { check_root_obj_specific_ref (root, (GCObject *)*ptr, key); ++ptr; } } SGEN_HASH_TABLE_FOREACH_END; if (sgen_is_world_stopped ()) find_pinning_ref_from_thread ((char*)key, sizeof (GCObject)); } #ifndef SGEN_WITHOUT_MONO static MonoDomain *check_domain = NULL; static void check_obj_not_in_domain (MonoObject **o) { g_assert (((*o))->vtable->domain != check_domain); } static void check_obj_not_in_domain_callback (GCObject **o, void *gc_data) { g_assert ((*o)->vtable->domain != check_domain); } void sgen_scan_for_registered_roots_in_domain (MonoDomain *domain, int root_type) { void **start_root; RootRecord *root; check_domain = domain; SGEN_HASH_TABLE_FOREACH (&sgen_roots_hash [root_type], void **, start_root, RootRecord *, root) { SgenDescriptor desc = root->root_desc; /* The MonoDomain struct is allowed to hold references to objects in its own domain. */ if (start_root == (void**)domain) continue; switch (desc & ROOT_DESC_TYPE_MASK) { case ROOT_DESC_BITMAP: desc >>= ROOT_DESC_TYPE_SHIFT; while (desc) { if ((desc & 1) && *start_root) check_obj_not_in_domain ((MonoObject **)*start_root); desc >>= 1; start_root++; } break; case ROOT_DESC_COMPLEX: { gsize *bitmap_data = (gsize *)sgen_get_complex_descriptor_bitmap (desc); int bwords = (int)((*bitmap_data) - 1); void **start_run = start_root; bitmap_data++; while (bwords-- > 0) { gsize bmap = *bitmap_data++; void **objptr = start_run; while (bmap) { if ((bmap & 1) && *objptr) check_obj_not_in_domain ((MonoObject **)*objptr); bmap >>= 1; ++objptr; } start_run += GC_BITS_PER_WORD; } break; } case ROOT_DESC_VECTOR: { void **p; for (p = start_root; p < (void**)root->end_root; p++) { if (*p) check_obj_not_in_domain ((MonoObject **)*p); } break; } case ROOT_DESC_USER: { SgenUserRootMarkFunc marker = sgen_get_user_descriptor_func (desc); marker (start_root, check_obj_not_in_domain_callback, NULL); break; } case ROOT_DESC_RUN_LEN: g_assert_not_reached (); default: g_assert_not_reached (); } } SGEN_HASH_TABLE_FOREACH_END; check_domain = NULL; } static gboolean is_xdomain_ref_allowed (GCObject **ptr, GCObject *obj, MonoDomain *domain) { return FALSE; } static void check_reference_for_xdomain (GCObject **ptr, GCObject *obj, MonoDomain *domain) { MonoObject *ref = *ptr; size_t offset = (char*)(ptr) - (char*)obj; MonoClass *klass; MonoClassField *field; char *str; if (!ref || ref->vtable->domain == domain) return; if (is_xdomain_ref_allowed (ptr, obj, domain)) return; field = NULL; for (klass = obj->vtable->klass; klass; klass = m_class_get_parent (klass)) { int i; int fcount = mono_class_get_field_count (klass); MonoClassField *klass_fields = m_class_get_fields (klass); for (i = 0; i < fcount; ++i) { if (klass_fields[i].offset == offset) { field = &klass_fields[i]; break; } } if (field) break; } if (ref->vtable->klass == mono_defaults.string_class) { ERROR_DECL (error); str = mono_string_to_utf8_checked_internal ((MonoString*)ref, error); mono_error_cleanup (error); } else str = NULL; g_print ("xdomain reference in %p (%s.%s) at offset %zu (%s) to %p (%s.%s) (%s) - pointed to by:\n", obj, m_class_get_name_space (obj->vtable->klass), m_class_get_name (obj->vtable->klass), offset, field ? field->name : "", ref, m_class_get_name_space (ref->vtable->klass), m_class_get_name (ref->vtable->klass), str ? str : ""); mono_gc_scan_for_specific_ref (obj, TRUE); if (str) g_free (str); } #undef HANDLE_PTR #define HANDLE_PTR(ptr,obj) check_reference_for_xdomain ((ptr), (obj), domain) static void scan_object_for_xdomain_refs (GCObject *obj, mword size, void *data) { char *start = (char*)obj; MonoVTable *vt = SGEN_LOAD_VTABLE (obj); MonoDomain *domain = vt->domain; SgenDescriptor desc = sgen_vtable_get_descriptor (vt); #include "sgen-scan-object.h" } void sgen_check_for_xdomain_refs (void) { sgen_scan_area_with_callback (sgen_nursery_section->data, sgen_nursery_section->end_data, (IterateObjectCallbackFunc)scan_object_for_xdomain_refs, NULL, FALSE, TRUE); sgen_major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_ALL, (IterateObjectCallbackFunc)scan_object_for_xdomain_refs, NULL); sgen_los_iterate_objects ((IterateObjectCallbackFunc)scan_object_for_xdomain_refs, NULL); } #endif /* If not null, dump the heap after each collection into this file */ static FILE *heap_dump_file = NULL; void sgen_dump_occupied (char *start, char *end, char *section_start) { fprintf (heap_dump_file, "<occupied offset=\"%ld\" size=\"%ld\"/>\n", (long)(start - section_start), (long)(end - start)); } void sgen_dump_section (GCMemSection *section, const char *type) { char *start = section->data; char *end = section->end_data; char *occ_start = NULL; fprintf (heap_dump_file, "<section type=\"%s\" size=\"%lu\">\n", type, (unsigned long)(section->end_data - section->data)); while (start < end) { guint size; //GCVTable vt; //MonoClass *class; if (!*(void**)start) { if (occ_start) { sgen_dump_occupied (occ_start, start, section->data); occ_start = NULL; } start += sizeof (void*); /* should be ALLOC_ALIGN, really */ continue; } if (!occ_start) occ_start = start; //vt = SGEN_LOAD_VTABLE (start); //class = vt->klass; size = SGEN_ALIGN_UP (safe_object_get_size ((GCObject*) start)); /* fprintf (heap_dump_file, "<object offset=\"%d\" class=\"%s.%s\" size=\"%d\"/>\n", start - section->data, vt->klass->name_space, vt->klass->name, size); */ start += size; } if (occ_start) sgen_dump_occupied (occ_start, start, section->data); fprintf (heap_dump_file, "</section>\n"); } static void dump_object (GCObject *obj, gboolean dump_location) { #ifndef SGEN_WITHOUT_MONO static char class_name [1024]; MonoClass *klass = mono_object_class (obj); int i, j; /* * Python's XML parser is too stupid to parse angle brackets * in strings, so we just ignore them; */ i = j = 0; while (m_class_get_name (klass) [i] && j < sizeof (class_name) - 1) { if (!strchr ("<>\"", m_class_get_name (klass) [i])) class_name [j++] = m_class_get_name (klass) [i]; ++i; } g_assert (j < sizeof (class_name)); class_name [j] = 0; fprintf (heap_dump_file, "<object class=\"%s.%s\" size=\"%ld\"", m_class_get_name_space (klass), class_name, (long)safe_object_get_size (obj)); if (dump_location) { const char *location; if (sgen_ptr_in_nursery (obj)) location = "nursery"; else if (safe_object_get_size (obj) <= SGEN_MAX_SMALL_OBJ_SIZE) location = "major"; else location = "LOS"; fprintf (heap_dump_file, " location=\"%s\"", location); } fprintf (heap_dump_file, "/>\n"); #endif } static void dump_object_callback (GCObject *obj, size_t size, gboolean dump_location) { dump_object (obj, dump_location); } void sgen_debug_enable_heap_dump (const char *filename) { heap_dump_file = fopen (filename, "w"); if (heap_dump_file) { fprintf (heap_dump_file, "<sgen-dump>\n"); sgen_pin_stats_enable (); } } void sgen_debug_dump_heap (const char *type, int num, const char *reason) { SgenPointerQueue *pinned_objects; int i; if (!heap_dump_file) return; fprintf (heap_dump_file, "<collection type=\"%s\" num=\"%d\"", type, num); if (reason) fprintf (heap_dump_file, " reason=\"%s\"", reason); fprintf (heap_dump_file, ">\n"); #ifndef SGEN_WITHOUT_MONO fprintf (heap_dump_file, "<other-mem-usage type=\"mempools\" size=\"%ld\"/>\n", mono_mempool_get_bytes_allocated ()); #endif sgen_dump_internal_mem_usage (heap_dump_file); fprintf (heap_dump_file, "<pinned type=\"stack\" bytes=\"%lu\"/>\n", (unsigned long)sgen_pin_stats_get_pinned_byte_count (PIN_TYPE_STACK)); /* fprintf (heap_dump_file, "<pinned type=\"static-data\" bytes=\"%d\"/>\n", pinned_byte_counts [PIN_TYPE_STATIC_DATA]); */ fprintf (heap_dump_file, "<pinned type=\"other\" bytes=\"%lu\"/>\n", (unsigned long)sgen_pin_stats_get_pinned_byte_count (PIN_TYPE_OTHER)); fprintf (heap_dump_file, "<pinned-objects>\n"); pinned_objects = sgen_pin_stats_get_object_list (); for (i = 0; i < pinned_objects->next_slot; ++i) dump_object ((GCObject *)pinned_objects->data [i], TRUE); fprintf (heap_dump_file, "</pinned-objects>\n"); sgen_dump_section (sgen_nursery_section, "nursery"); sgen_major_collector.dump_heap (heap_dump_file); fprintf (heap_dump_file, "<los>\n"); sgen_los_iterate_objects ((IterateObjectCallbackFunc)dump_object_callback, (void*)FALSE); fprintf (heap_dump_file, "</los>\n"); fprintf (heap_dump_file, "</collection>\n"); } static GCObject *found_obj; static void find_object_for_ptr_callback (GCObject *obj, size_t size, void *user_data) { char *ptr = (char *)user_data; if (ptr >= (char*)obj && ptr < (char*)obj + size) { g_assert (!found_obj); found_obj = obj; } } /* for use in the debugger */ GCObject* sgen_find_object_for_ptr (char *ptr) { if (ptr >= sgen_nursery_section->data && ptr < sgen_nursery_section->end_data) { found_obj = NULL; sgen_scan_area_with_callback (sgen_nursery_section->data, sgen_nursery_section->end_data, find_object_for_ptr_callback, ptr, TRUE, FALSE); if (found_obj) return found_obj; } found_obj = NULL; sgen_los_iterate_objects (find_object_for_ptr_callback, ptr); if (found_obj) return found_obj; /* * Very inefficient, but this is debugging code, supposed to * be called from gdb, so we don't care. */ found_obj = NULL; sgen_major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_ALL, find_object_for_ptr_callback, ptr); return found_obj; } #else void sgen_check_for_xdomain_refs (void) { } void sgen_check_heap_marked (gboolean nursery_must_be_pinned) { } void sgen_check_major_refs (void) { } void sgen_check_mod_union_consistency (void) { } void sgen_check_nursery_objects_untag (void) { } void sgen_check_remset_consistency (void) { } void sgen_check_whole_heap (gboolean allow_missing_pinned) { } void sgen_debug_check_nursery_is_clean (void) { } void sgen_debug_dump_heap (const char *type, int num, const char *reason) { } void sgen_debug_enable_heap_dump (const char *filename) { } void sgen_debug_verify_nursery (gboolean do_dump_nursery_content) { } void sgen_dump_occupied (char *start, char *end, char *section_start) { } void sgen_scan_for_registered_roots_in_domain (MonoDomain *domain, int root_type) { } #endif /*DISABLE_SGEN_DEBUG_HELPERS */ #endif /*HAVE_SGEN_GC*/
/** * \file * Collector debugging * * Author: * Paolo Molaro ([email protected]) * Rodrigo Kumpera ([email protected]) * * Copyright 2005-2011 Novell, Inc (http://www.novell.com) * Copyright 2011 Xamarin Inc (http://www.xamarin.com) * Copyright 2011 Xamarin, Inc. * Copyright (C) 2012 Xamarin Inc * * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #include "config.h" #ifdef HAVE_SGEN_GC #include <string.h> #include "mono/sgen/sgen-gc.h" #include "mono/sgen/sgen-cardtable.h" #include "mono/sgen/sgen-protocol.h" #include "mono/sgen/sgen-memory-governor.h" #include "mono/sgen/sgen-pinning.h" #include "mono/sgen/sgen-client.h" #if _MSC_VER #pragma warning(disable:4312) // FIXME pointer cast to different size #endif #ifndef DISABLE_SGEN_DEBUG_HELPERS #define LOAD_VTABLE SGEN_LOAD_VTABLE #define object_is_forwarded SGEN_OBJECT_IS_FORWARDED #define object_is_pinned SGEN_OBJECT_IS_PINNED #define safe_object_get_size sgen_safe_object_get_size void sgen_describe_ptr (char *ptr); void sgen_check_object (GCObject *obj); /* * ###################################################################### * ######## Collector debugging * ###################################################################### */ static const char*descriptor_types [] = { "INVALID", "run length", "bitmap", "small pointer-free", "complex", "vector", "complex arrray", "complex pointer-free" }; static char* describe_nursery_ptr (char *ptr, gboolean need_setup); static void describe_pointer (char *ptr, gboolean need_setup) { GCVTable vtable; SgenDescriptor desc; int type; char *start; char *forwarded; mword size; restart: if (sgen_ptr_in_nursery (ptr)) { start = describe_nursery_ptr (ptr, need_setup); if (!start) return; ptr = start; vtable = LOAD_VTABLE ((GCObject*)ptr); } else { if (sgen_ptr_is_in_los (ptr, &start)) { if (ptr == start) printf ("Pointer is the start of object %p in LOS space.\n", start); else printf ("Pointer is at offset 0x%x of object %p in LOS space.\n", (int)(ptr - start), start); ptr = start; mono_sgen_los_describe_pointer (ptr); vtable = LOAD_VTABLE ((GCObject*)ptr); } else if (sgen_major_collector.ptr_is_in_non_pinned_space (ptr, &start)) { if (ptr == start) printf ("Pointer is the start of object %p in oldspace.\n", start); else if (start) printf ("Pointer is at offset 0x%x of object %p in oldspace.\n", (int)(ptr - start), start); else printf ("Pointer inside oldspace.\n"); if (start) ptr = start; vtable = (GCVTable)sgen_major_collector.describe_pointer (ptr); } else if (sgen_major_collector.ptr_is_from_pinned_alloc (ptr)) { // FIXME: Handle pointers to the inside of objects printf ("Pointer is inside a pinned chunk.\n"); vtable = LOAD_VTABLE ((GCObject*)ptr); } else { printf ("Pointer unknown.\n"); return; } } if (object_is_pinned (ptr)) printf ("Object is pinned.\n"); if ((forwarded = (char *)object_is_forwarded (ptr))) { printf ("Object is forwarded to %p:\n", forwarded); ptr = forwarded; goto restart; } printf ("VTable: %p\n", vtable); if (vtable == NULL) { printf ("VTable is invalid (empty).\n"); goto invalid_vtable; } if (sgen_ptr_in_nursery (vtable)) { printf ("VTable is invalid (points inside nursery).\n"); goto invalid_vtable; } printf ("Class: %s.%s\n", sgen_client_vtable_get_namespace (vtable), sgen_client_vtable_get_name (vtable)); desc = sgen_vtable_get_descriptor (vtable); printf ("Descriptor: %lx\n", (long)desc); type = desc & DESC_TYPE_MASK; printf ("Descriptor type: %d (%s)\n", type, descriptor_types [type]); size = sgen_safe_object_get_size ((GCObject*)ptr); printf ("Size: %d\n", (int)size); invalid_vtable: ; sgen_client_describe_invalid_pointer ((GCObject *) ptr); } void sgen_describe_ptr (char *ptr) { describe_pointer (ptr, TRUE); } static gboolean missing_remsets; /* * We let a missing remset slide if the target object is pinned, * because the store might have happened but the remset not yet added, * but in that case the target must be pinned. We might theoretically * miss some missing remsets this way, but it's very unlikely. */ #undef HANDLE_PTR #define HANDLE_PTR(ptr,obj) do { \ if (*(ptr) && sgen_ptr_in_nursery ((char*)*(ptr))) { \ if (!sgen_get_remset ()->find_address ((char*)(ptr)) && !sgen_cement_lookup (*(ptr))) { \ GCVTable __vt = SGEN_LOAD_VTABLE (obj); \ gboolean is_pinned = object_is_pinned (*(ptr)); \ SGEN_LOG (0, "Oldspace->newspace reference %p at offset %ld in object %p (%s.%s) not found in remsets%s.", *(ptr), (long)((char*)(ptr) - (char*)(obj)), (obj), sgen_client_vtable_get_namespace (__vt), sgen_client_vtable_get_name (__vt), is_pinned ? ", but object is pinned" : ""); \ sgen_binary_protocol_missing_remset ((obj), __vt, (int) ((char*)(ptr) - (char*)(obj)), *(ptr), (gpointer)LOAD_VTABLE(*(ptr)), is_pinned); \ if (!is_pinned) \ missing_remsets = TRUE; \ } \ } \ } while (0) /* * Check that each object reference which points into the nursery can * be found in the remembered sets. */ static void check_consistency_callback (GCObject *obj, size_t size, void *dummy) { char *start = (char*)obj; GCVTable vt = LOAD_VTABLE (obj); SgenDescriptor desc = sgen_vtable_get_descriptor (vt); SGEN_LOG (8, "Scanning object %p, vtable: %p (%s)", start, vt, sgen_client_vtable_get_name (vt)); #include "sgen-scan-object.h" } /* * Perform consistency check of the heap. * * Assumes the world is stopped. */ void sgen_check_remset_consistency (void) { // Need to add more checks missing_remsets = FALSE; SGEN_LOG (1, "Begin heap consistency check..."); // Check that oldspace->newspace pointers are registered with the collector sgen_major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_ALL, (IterateObjectCallbackFunc)check_consistency_callback, NULL); sgen_los_iterate_objects ((IterateObjectCallbackFunc)check_consistency_callback, NULL); SGEN_LOG (1, "Heap consistency check done."); if (missing_remsets) sgen_binary_protocol_flush_buffers (TRUE); if (!sgen_binary_protocol_is_enabled ()) g_assert (!missing_remsets); } static gboolean is_major_or_los_object_marked (GCObject *obj) { if (sgen_safe_object_get_size ((GCObject*)obj) > SGEN_MAX_SMALL_OBJ_SIZE) { return sgen_los_object_is_pinned (obj); } else { return sgen_get_major_collector ()->is_object_live (obj); } } #undef HANDLE_PTR #define HANDLE_PTR(ptr,obj) do { \ if (*(ptr) && !sgen_ptr_in_nursery ((char*)*(ptr)) && !is_major_or_los_object_marked ((GCObject*)*(ptr))) { \ if (!cards || !sgen_get_remset ()->find_address_with_cards (start, cards, (char*)(ptr))) { \ GCVTable __vt = SGEN_LOAD_VTABLE (obj); \ SGEN_LOG (0, "major->major reference %p at offset %ld in object %p (%s.%s) not found in remsets.", *(ptr), (long)((char*)(ptr) - (char*)(obj)), (obj), sgen_client_vtable_get_namespace (__vt), sgen_client_vtable_get_name (__vt)); \ sgen_binary_protocol_missing_remset ((obj), __vt, (int) ((char*)(ptr) - (char*)(obj)), *(ptr), (gpointer)LOAD_VTABLE(*(ptr)), object_is_pinned (*(ptr))); \ missing_remsets = TRUE; \ } \ } \ } while (0) static void check_mod_union_callback (GCObject *obj, size_t size, void *dummy) { char *start = (char*)obj; gboolean in_los = (gboolean) (size_t) dummy; GCVTable vt = LOAD_VTABLE (obj); SgenDescriptor desc = sgen_vtable_get_descriptor (vt); guint8 *cards; SGEN_LOG (8, "Scanning object %p, vtable: %p (%s)", obj, vt, sgen_client_vtable_get_name (vt)); if (!is_major_or_los_object_marked (obj)) return; if (in_los) cards = sgen_los_header_for_object (obj)->cardtable_mod_union; else cards = sgen_get_major_collector ()->get_cardtable_mod_union_for_reference (start); #include "sgen-scan-object.h" } void sgen_check_mod_union_consistency (void) { missing_remsets = FALSE; sgen_major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_ALL, (IterateObjectCallbackFunc)check_mod_union_callback, (void*)FALSE); sgen_los_iterate_objects ((IterateObjectCallbackFunc)check_mod_union_callback, (void*)TRUE); if (!sgen_binary_protocol_is_enabled ()) g_assert (!missing_remsets); } #undef HANDLE_PTR #define HANDLE_PTR(ptr,obj) do { \ if (*(ptr) && !LOAD_VTABLE (*(ptr))) \ g_error ("Could not load vtable for obj %p slot %ld (size %ld)", obj, (long)((char*)ptr - (char*)obj), (long)safe_object_get_size ((GCObject*)obj)); \ } while (0) static void check_major_refs_callback (GCObject *obj, size_t size, void *dummy) { char *start = (char*)obj; SgenDescriptor desc = sgen_obj_get_descriptor (obj); #include "sgen-scan-object.h" } void sgen_check_major_refs (void) { sgen_major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_ALL, (IterateObjectCallbackFunc)check_major_refs_callback, NULL); sgen_los_iterate_objects ((IterateObjectCallbackFunc)check_major_refs_callback, NULL); } /* Check that the reference is valid */ #undef HANDLE_PTR #define HANDLE_PTR(ptr,obj) do { \ if (*(ptr)) { \ g_assert (sgen_client_vtable_get_namespace (SGEN_LOAD_VTABLE_UNCHECKED (*(ptr)))); \ } \ } while (0) /* * sgen_check_object: * * Perform consistency check on an object. Currently we only check that the * reference fields are valid. */ void sgen_check_object (GCObject *obj) { char *start = (char*)obj; SgenDescriptor desc; if (!start) return; desc = sgen_obj_get_descriptor (obj); #include "sgen-scan-object.h" } static GCObject **valid_nursery_objects; static int valid_nursery_object_count; static gboolean broken_heap; static void setup_mono_sgen_scan_area_with_callback (GCObject *object, size_t size, void *data) { valid_nursery_objects [valid_nursery_object_count++] = object; } static void setup_valid_nursery_objects (void) { if (!valid_nursery_objects) valid_nursery_objects = (GCObject **)sgen_alloc_os_memory (sgen_nursery_max_size, (SgenAllocFlags)(SGEN_ALLOC_INTERNAL | SGEN_ALLOC_ACTIVATE), "debugging data", MONO_MEM_ACCOUNT_SGEN_DEBUGGING); valid_nursery_object_count = 0; sgen_scan_area_with_callback (sgen_nursery_section->data, sgen_nursery_section->end_data, setup_mono_sgen_scan_area_with_callback, NULL, FALSE, FALSE); } static gboolean find_object_in_nursery_dump (char *object) { int first = 0, last = valid_nursery_object_count; while (first < last) { int middle = first + ((last - first) >> 1); if (object == (char*)valid_nursery_objects [middle]) return TRUE; if (object < (char*)valid_nursery_objects [middle]) last = middle; else first = middle + 1; } g_assert (first == last); return FALSE; } static void iterate_valid_nursery_objects (IterateObjectCallbackFunc callback, void *data) { int i; for (i = 0; i < valid_nursery_object_count; ++i) { GCObject *obj = valid_nursery_objects [i]; callback (obj, safe_object_get_size (obj), data); } } static char* describe_nursery_ptr (char *ptr, gboolean need_setup) { int i; if (need_setup) setup_valid_nursery_objects (); for (i = 0; i < valid_nursery_object_count - 1; ++i) { if ((char*)valid_nursery_objects [i + 1] > ptr) break; } if (i >= valid_nursery_object_count || (char*)valid_nursery_objects [i] + safe_object_get_size (valid_nursery_objects [i]) < ptr) { SGEN_LOG (0, "nursery-ptr (unalloc'd-memory)"); return NULL; } else { GCObject *obj = valid_nursery_objects [i]; if ((char*)obj == ptr) SGEN_LOG (0, "nursery-ptr %p", obj); else SGEN_LOG (0, "nursery-ptr %p (interior-ptr offset %ld)", obj, (long)(ptr - (char*)obj)); return (char*)obj; } } static gboolean is_valid_object_pointer (char *object) { if (sgen_ptr_in_nursery (object)) return find_object_in_nursery_dump (object); if (sgen_los_is_valid_object (object)) return TRUE; if (sgen_major_collector.is_valid_object (object)) return TRUE; return FALSE; } static void bad_pointer_spew (char *obj, char **slot) { char *ptr = *slot; GCVTable vtable = LOAD_VTABLE ((GCObject*)obj); SGEN_LOG (0, "Invalid object pointer %p at offset %ld in object %p (%s.%s):", ptr, (long)((char*)slot - obj), obj, sgen_client_vtable_get_namespace (vtable), sgen_client_vtable_get_name (vtable)); describe_pointer (ptr, FALSE); broken_heap = TRUE; } static void missing_remset_spew (char *obj, char **slot) { char *ptr = *slot; GCVTable vtable = LOAD_VTABLE ((GCObject*)obj); SGEN_LOG (0, "Oldspace->newspace reference %p at offset %ld in object %p (%s.%s) not found in remsets.", ptr, (long)((char*)slot - obj), obj, sgen_client_vtable_get_namespace (vtable), sgen_client_vtable_get_name (vtable)); broken_heap = TRUE; } /* FIXME Flag missing remsets due to pinning as non fatal */ #undef HANDLE_PTR #define HANDLE_PTR(ptr,obj) do { \ if (*(char**)ptr) { \ if (!is_valid_object_pointer (*(char**)ptr)) { \ bad_pointer_spew ((char*)obj, (char**)ptr); \ } else if (!sgen_ptr_in_nursery (obj) && sgen_ptr_in_nursery ((char*)*ptr)) { \ if (!allow_missing_pinned && !SGEN_OBJECT_IS_PINNED (*(ptr)) && !sgen_get_remset ()->find_address ((char*)(ptr)) && !sgen_cement_lookup (*(ptr))) \ missing_remset_spew ((char*)obj, (char**)ptr); \ } \ } \ } while (0) static void verify_object_pointers_callback (GCObject *obj, size_t size, void *data) { char *start = (char*)obj; gboolean allow_missing_pinned = (gboolean) (size_t) data; SgenDescriptor desc = sgen_obj_get_descriptor_safe (obj); #include "sgen-scan-object.h" } /* FIXME: -This heap checker is racy regarding inlined write barriers and other JIT tricks that depend on OP_DUMMY_USE. */ void sgen_check_whole_heap (gboolean allow_missing_pinned) { setup_valid_nursery_objects (); broken_heap = FALSE; sgen_scan_area_with_callback (sgen_nursery_section->data, sgen_nursery_section->end_data, verify_object_pointers_callback, (void*) (size_t) allow_missing_pinned, FALSE, TRUE); sgen_major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_ALL, verify_object_pointers_callback, (void*) (size_t) allow_missing_pinned); sgen_los_iterate_objects (verify_object_pointers_callback, (void*) (size_t) allow_missing_pinned); g_assert (!broken_heap); } static gboolean ptr_in_heap (char *object) { if (sgen_ptr_in_nursery (object)) return TRUE; if (sgen_los_is_valid_object (object)) return TRUE; if (sgen_major_collector.is_valid_object (object)) return TRUE; return FALSE; } /* * sgen_check_objref: * Do consistency checks on the object reference OBJ. Assert on failure. */ void sgen_check_objref (char *obj) { g_assert (ptr_in_heap (obj)); } static void find_pinning_ref_from_thread (char *obj, size_t size) { #ifndef SGEN_WITHOUT_MONO char *endobj = obj + size; FOREACH_THREAD_EXCLUDE (info, MONO_THREAD_INFO_FLAGS_NO_GC) { mword *ctxstart, *ctxcurrent, *ctxend; char **start = (char**)info->client_info.stack_start; if (info->client_info.skip) continue; while (start < (char**)info->client_info.info.stack_end) { if (*start >= obj && *start < endobj) SGEN_LOG (0, "Object %p referenced in thread %p (id %p) at %p, stack: %p-%p", obj, info, (gpointer)(gsize) mono_thread_info_get_tid (info), start, info->client_info.stack_start, info->client_info.info.stack_end); start++; } for (ctxstart = ctxcurrent = (mword*) &info->client_info.ctx, ctxend = (mword*) (&info->client_info.ctx + 1); ctxcurrent < ctxend; ctxcurrent ++) { mword w = *ctxcurrent; if (w >= (mword)obj && w < (mword)obj + size) SGEN_LOG (0, "Object %p referenced in saved reg %d of thread %p (id %p)", obj, (int) (ctxcurrent - ctxstart), info, (gpointer)(gsize) mono_thread_info_get_tid (info)); } } FOREACH_THREAD_END #endif } /* * Debugging function: find in the conservative roots where @obj is being pinned. */ static G_GNUC_UNUSED void find_pinning_reference (char *obj, size_t size) { char **start; RootRecord *root; char *endobj = obj + size; SGEN_HASH_TABLE_FOREACH (&sgen_roots_hash [ROOT_TYPE_NORMAL], char **, start, RootRecord *, root) { /* if desc is non-null it has precise info */ if (!root->root_desc) { while (start < (char**)root->end_root) { if (*start >= obj && *start < endobj) { SGEN_LOG (0, "Object %p referenced in pinned roots %p-%p\n", obj, start, root->end_root); } start++; } } } SGEN_HASH_TABLE_FOREACH_END; find_pinning_ref_from_thread (obj, size); } #undef HANDLE_PTR #define HANDLE_PTR(ptr,obj) do { \ char* __target = *(char**)ptr; \ if (__target) { \ if (sgen_ptr_in_nursery (__target)) { \ g_assert (!SGEN_OBJECT_IS_FORWARDED (__target)); \ } else { \ mword __size = sgen_safe_object_get_size ((GCObject*)__target); \ if (__size <= SGEN_MAX_SMALL_OBJ_SIZE) \ g_assert (sgen_major_collector.is_object_live ((GCObject*)__target)); \ else \ g_assert (sgen_los_object_is_pinned ((GCObject*)__target)); \ } \ } \ } while (0) static void check_marked_callback (GCObject *obj, size_t size, void *dummy) { char *start = (char*)obj; gboolean flag = (gboolean) (size_t) dummy; SgenDescriptor desc; if (sgen_ptr_in_nursery (start)) { if (flag) SGEN_ASSERT (0, SGEN_OBJECT_IS_PINNED (obj), "All objects remaining in the nursery must be pinned"); } else if (flag) { if (!sgen_los_object_is_pinned (obj)) return; } else { if (!sgen_major_collector.is_object_live (obj)) return; } desc = sgen_obj_get_descriptor_safe (obj); #include "sgen-scan-object.h" } void sgen_check_heap_marked (gboolean nursery_must_be_pinned) { setup_valid_nursery_objects (); iterate_valid_nursery_objects (check_marked_callback, (void*)(size_t)nursery_must_be_pinned); sgen_major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_ALL, check_marked_callback, (void*)FALSE); sgen_los_iterate_objects (check_marked_callback, (void*)TRUE); } static void check_nursery_objects_untag_callback (char *obj, size_t size, void *data) { g_assert (!SGEN_OBJECT_IS_FORWARDED (obj)); g_assert (!SGEN_OBJECT_IS_PINNED (obj)); } void sgen_check_nursery_objects_untag (void) { sgen_clear_nursery_fragments (); sgen_scan_area_with_callback (sgen_nursery_section->data, sgen_nursery_section->end_data, (IterateObjectCallbackFunc)check_nursery_objects_untag_callback, NULL, FALSE, TRUE); } static void verify_scan_starts (char *start, char *end) { size_t i; for (i = 0; i < sgen_nursery_section->num_scan_start; ++i) { char *addr = sgen_nursery_section->scan_starts [i]; if (addr > start && addr < end) SGEN_LOG (0, "NFC-BAD SCAN START [%lu] %p for obj [%p %p]", (unsigned long)i, addr, start, end); } } void sgen_debug_verify_nursery (gboolean do_dump_nursery_content) { char *start, *end, *cur, *hole_start; if (sgen_nursery_canaries_enabled ()) SGEN_LOG (0, "Checking nursery canaries..."); /*This cleans up unused fragments */ sgen_nursery_allocator_prepare_for_pinning (); hole_start = start = cur = sgen_get_nursery_start (); end = sgen_get_nursery_end (); while (cur < end) { size_t ss, size; gboolean is_array_fill; if (!*(void**)cur) { cur += sizeof (void*); continue; } if (object_is_forwarded (cur)) SGEN_LOG (0, "FORWARDED OBJ %p", cur); else if (object_is_pinned (cur)) SGEN_LOG (0, "PINNED OBJ %p", cur); ss = safe_object_get_size ((GCObject*)cur); size = SGEN_ALIGN_UP (ss); verify_scan_starts (cur, cur + size); is_array_fill = sgen_client_object_is_array_fill ((GCObject*)cur); if (do_dump_nursery_content) { GCVTable vtable = SGEN_LOAD_VTABLE ((GCObject*)cur); if (cur > hole_start) SGEN_LOG (0, "HOLE [%p %p %d]", hole_start, cur, (int)(cur - hole_start)); SGEN_LOG (0, "OBJ [%p %p %d %d %s.%s %d]", cur, cur + size, (int)size, (int)ss, sgen_client_vtable_get_namespace (vtable), sgen_client_vtable_get_name (vtable), is_array_fill); } if (sgen_nursery_canaries_enabled () && !is_array_fill) { CHECK_CANARY_FOR_OBJECT ((GCObject*)cur, TRUE); CANARIFY_SIZE (size); } cur += size; hole_start = cur; } } /* * Checks that no objects in the nursery are fowarded or pinned. This * is a precondition to restarting the mutator while doing a * concurrent collection. Note that we don't clear fragments because * we depend on that having happened earlier. */ void sgen_debug_check_nursery_is_clean (void) { char *end, *cur; cur = sgen_get_nursery_start (); end = sgen_get_nursery_end (); while (cur < end) { size_t size; if (!*(void**)cur) { cur += sizeof (void*); continue; } g_assert (!object_is_forwarded (cur)); g_assert (!object_is_pinned (cur)); size = SGEN_ALIGN_UP (safe_object_get_size ((GCObject*)cur)); verify_scan_starts (cur, cur + size); cur += size; } } static gboolean scan_object_for_specific_ref_precise = TRUE; #undef HANDLE_PTR #define HANDLE_PTR(ptr,obj) do { \ if ((GCObject*)*(ptr) == key) { \ GCVTable vtable = SGEN_LOAD_VTABLE (*(ptr)); \ g_print ("found ref to %p in object %p (%s.%s) at offset %ld\n", \ key, (obj), sgen_client_vtable_get_namespace (vtable), sgen_client_vtable_get_name (vtable), (long)(((char*)(ptr) - (char*)(obj)))); \ } \ } while (0) static void scan_object_for_specific_ref (GCObject *obj, GCObject *key) { GCObject *forwarded; if ((forwarded = SGEN_OBJECT_IS_FORWARDED (obj))) obj = forwarded; if (scan_object_for_specific_ref_precise) { char *start = (char*)obj; SgenDescriptor desc = sgen_obj_get_descriptor_safe (obj); #include "sgen-scan-object.h" } else { mword *words = (mword*)obj; size_t size = safe_object_get_size (obj); int i; for (i = 0; i < size / sizeof (mword); ++i) { if (words [i] == (mword)key) { GCVTable vtable = SGEN_LOAD_VTABLE (obj); g_print ("found possible ref to %p in object %p (%s.%s) at offset %ld\n", key, obj, sgen_client_vtable_get_namespace (vtable), sgen_client_vtable_get_name (vtable), (long)(i * sizeof (mword))); } } } } static void scan_object_for_specific_ref_callback (GCObject *obj, size_t size, GCObject *key) { scan_object_for_specific_ref (obj, key); } static void check_root_obj_specific_ref (RootRecord *root, GCObject *key, GCObject *obj) { if (key != obj) return; g_print ("found ref to %p in root record %p\n", key, root); } static GCObject *check_key = NULL; static RootRecord *check_root = NULL; static void check_root_obj_specific_ref_from_marker (GCObject **obj, void *gc_data) { check_root_obj_specific_ref (check_root, check_key, *obj); } static void scan_roots_for_specific_ref (GCObject *key, int root_type) { void **start_root; RootRecord *root; check_key = key; SGEN_HASH_TABLE_FOREACH (&sgen_roots_hash [root_type], void **, start_root, RootRecord *, root) { SgenDescriptor desc = root->root_desc; check_root = root; switch (desc & ROOT_DESC_TYPE_MASK) { case ROOT_DESC_BITMAP: desc >>= ROOT_DESC_TYPE_SHIFT; while (desc) { if (desc & 1) check_root_obj_specific_ref (root, key, (GCObject *)*start_root); desc >>= 1; start_root++; } return; case ROOT_DESC_COMPLEX: { gsize *bitmap_data = (gsize *)sgen_get_complex_descriptor_bitmap (desc); int bwords = (int) ((*bitmap_data) - 1); void **start_run = start_root; bitmap_data++; while (bwords-- > 0) { gsize bmap = *bitmap_data++; void **objptr = start_run; while (bmap) { if (bmap & 1) check_root_obj_specific_ref (root, key, (GCObject *)*objptr); bmap >>= 1; ++objptr; } start_run += GC_BITS_PER_WORD; } break; } case ROOT_DESC_VECTOR: { void **p; for (p = start_root; p < (void**)root->end_root; p++) { if (*p) check_root_obj_specific_ref (root, key, (GCObject *)*p); } break; } case ROOT_DESC_USER: { SgenUserRootMarkFunc marker = sgen_get_user_descriptor_func (desc); marker (start_root, check_root_obj_specific_ref_from_marker, NULL); break; } case ROOT_DESC_RUN_LEN: g_assert_not_reached (); default: g_assert_not_reached (); } } SGEN_HASH_TABLE_FOREACH_END; check_key = NULL; check_root = NULL; } void mono_gc_scan_for_specific_ref (GCObject *key, gboolean precise) { void **ptr; RootRecord *root; scan_object_for_specific_ref_precise = precise; sgen_scan_area_with_callback (sgen_nursery_section->data, sgen_nursery_section->end_data, (IterateObjectCallbackFunc)scan_object_for_specific_ref_callback, key, TRUE, FALSE); sgen_major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_ALL, (IterateObjectCallbackFunc)scan_object_for_specific_ref_callback, key); sgen_los_iterate_objects ((IterateObjectCallbackFunc)scan_object_for_specific_ref_callback, key); scan_roots_for_specific_ref (key, ROOT_TYPE_NORMAL); scan_roots_for_specific_ref (key, ROOT_TYPE_WBARRIER); SGEN_HASH_TABLE_FOREACH (&sgen_roots_hash [ROOT_TYPE_PINNED], void **, ptr, RootRecord *, root) { while (ptr < (void**)root->end_root) { check_root_obj_specific_ref (root, (GCObject *)*ptr, key); ++ptr; } } SGEN_HASH_TABLE_FOREACH_END; if (sgen_is_world_stopped ()) find_pinning_ref_from_thread ((char*)key, sizeof (GCObject)); } #ifndef SGEN_WITHOUT_MONO static MonoDomain *check_domain = NULL; static void check_obj_not_in_domain (MonoObject **o) { g_assert (((*o))->vtable->domain != check_domain); } static void check_obj_not_in_domain_callback (GCObject **o, void *gc_data) { g_assert ((*o)->vtable->domain != check_domain); } void sgen_scan_for_registered_roots_in_domain (MonoDomain *domain, int root_type) { void **start_root; RootRecord *root; check_domain = domain; SGEN_HASH_TABLE_FOREACH (&sgen_roots_hash [root_type], void **, start_root, RootRecord *, root) { SgenDescriptor desc = root->root_desc; /* The MonoDomain struct is allowed to hold references to objects in its own domain. */ if (start_root == (void**)domain) continue; switch (desc & ROOT_DESC_TYPE_MASK) { case ROOT_DESC_BITMAP: desc >>= ROOT_DESC_TYPE_SHIFT; while (desc) { if ((desc & 1) && *start_root) check_obj_not_in_domain ((MonoObject **)*start_root); desc >>= 1; start_root++; } break; case ROOT_DESC_COMPLEX: { gsize *bitmap_data = (gsize *)sgen_get_complex_descriptor_bitmap (desc); int bwords = (int)((*bitmap_data) - 1); void **start_run = start_root; bitmap_data++; while (bwords-- > 0) { gsize bmap = *bitmap_data++; void **objptr = start_run; while (bmap) { if ((bmap & 1) && *objptr) check_obj_not_in_domain ((MonoObject **)*objptr); bmap >>= 1; ++objptr; } start_run += GC_BITS_PER_WORD; } break; } case ROOT_DESC_VECTOR: { void **p; for (p = start_root; p < (void**)root->end_root; p++) { if (*p) check_obj_not_in_domain ((MonoObject **)*p); } break; } case ROOT_DESC_USER: { SgenUserRootMarkFunc marker = sgen_get_user_descriptor_func (desc); marker (start_root, check_obj_not_in_domain_callback, NULL); break; } case ROOT_DESC_RUN_LEN: g_assert_not_reached (); default: g_assert_not_reached (); } } SGEN_HASH_TABLE_FOREACH_END; check_domain = NULL; } static gboolean is_xdomain_ref_allowed (GCObject **ptr, GCObject *obj, MonoDomain *domain) { return FALSE; } static void check_reference_for_xdomain (GCObject **ptr, GCObject *obj, MonoDomain *domain) { MonoObject *ref = *ptr; size_t offset = (char*)(ptr) - (char*)obj; MonoClass *klass; MonoClassField *field; char *str; if (!ref || ref->vtable->domain == domain) return; if (is_xdomain_ref_allowed (ptr, obj, domain)) return; field = NULL; for (klass = obj->vtable->klass; klass; klass = m_class_get_parent (klass)) { int i; int fcount = mono_class_get_field_count (klass); MonoClassField *klass_fields = m_class_get_fields (klass); for (i = 0; i < fcount; ++i) { if (klass_fields[i].offset == offset) { field = &klass_fields[i]; break; } } if (field) break; } if (ref->vtable->klass == mono_defaults.string_class) { ERROR_DECL (error); str = mono_string_to_utf8_checked_internal ((MonoString*)ref, error); mono_error_cleanup (error); } else str = NULL; g_print ("xdomain reference in %p (%s.%s) at offset %zu (%s) to %p (%s.%s) (%s) - pointed to by:\n", obj, m_class_get_name_space (obj->vtable->klass), m_class_get_name (obj->vtable->klass), offset, field ? field->name : "", ref, m_class_get_name_space (ref->vtable->klass), m_class_get_name (ref->vtable->klass), str ? str : ""); mono_gc_scan_for_specific_ref (obj, TRUE); if (str) g_free (str); } #undef HANDLE_PTR #define HANDLE_PTR(ptr,obj) check_reference_for_xdomain ((ptr), (obj), domain) static void scan_object_for_xdomain_refs (GCObject *obj, mword size, void *data) { char *start = (char*)obj; MonoVTable *vt = SGEN_LOAD_VTABLE (obj); MonoDomain *domain = vt->domain; SgenDescriptor desc = sgen_vtable_get_descriptor (vt); #include "sgen-scan-object.h" } void sgen_check_for_xdomain_refs (void) { sgen_scan_area_with_callback (sgen_nursery_section->data, sgen_nursery_section->end_data, (IterateObjectCallbackFunc)scan_object_for_xdomain_refs, NULL, FALSE, TRUE); sgen_major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_ALL, (IterateObjectCallbackFunc)scan_object_for_xdomain_refs, NULL); sgen_los_iterate_objects ((IterateObjectCallbackFunc)scan_object_for_xdomain_refs, NULL); } #endif /* If not null, dump the heap after each collection into this file */ static FILE *heap_dump_file = NULL; void sgen_dump_occupied (char *start, char *end, char *section_start) { fprintf (heap_dump_file, "<occupied offset=\"%ld\" size=\"%ld\"/>\n", (long)(start - section_start), (long)(end - start)); } void sgen_dump_section (GCMemSection *section, const char *type) { char *start = section->data; char *end = section->end_data; char *occ_start = NULL; fprintf (heap_dump_file, "<section type=\"%s\" size=\"%lu\">\n", type, (unsigned long)(section->end_data - section->data)); while (start < end) { guint size; //GCVTable vt; //MonoClass *class; if (!*(void**)start) { if (occ_start) { sgen_dump_occupied (occ_start, start, section->data); occ_start = NULL; } start += sizeof (void*); /* should be ALLOC_ALIGN, really */ continue; } if (!occ_start) occ_start = start; //vt = SGEN_LOAD_VTABLE (start); //class = vt->klass; size = SGEN_ALIGN_UP (safe_object_get_size ((GCObject*) start)); /* fprintf (heap_dump_file, "<object offset=\"%d\" class=\"%s.%s\" size=\"%d\"/>\n", start - section->data, vt->klass->name_space, vt->klass->name, size); */ start += size; } if (occ_start) sgen_dump_occupied (occ_start, start, section->data); fprintf (heap_dump_file, "</section>\n"); } static void dump_object (GCObject *obj, gboolean dump_location) { #ifndef SGEN_WITHOUT_MONO static char class_name [1024]; MonoClass *klass = mono_object_class (obj); int i, j; /* * Python's XML parser is too stupid to parse angle brackets * in strings, so we just ignore them; */ i = j = 0; while (m_class_get_name (klass) [i] && j < sizeof (class_name) - 1) { if (!strchr ("<>\"", m_class_get_name (klass) [i])) class_name [j++] = m_class_get_name (klass) [i]; ++i; } g_assert (j < sizeof (class_name)); class_name [j] = 0; fprintf (heap_dump_file, "<object class=\"%s.%s\" size=\"%ld\"", m_class_get_name_space (klass), class_name, (long)safe_object_get_size (obj)); if (dump_location) { const char *location; if (sgen_ptr_in_nursery (obj)) location = "nursery"; else if (safe_object_get_size (obj) <= SGEN_MAX_SMALL_OBJ_SIZE) location = "major"; else location = "LOS"; fprintf (heap_dump_file, " location=\"%s\"", location); } fprintf (heap_dump_file, "/>\n"); #endif } static void dump_object_callback (GCObject *obj, size_t size, gboolean dump_location) { dump_object (obj, dump_location); } void sgen_debug_enable_heap_dump (const char *filename) { heap_dump_file = fopen (filename, "w"); if (heap_dump_file) { fprintf (heap_dump_file, "<sgen-dump>\n"); sgen_pin_stats_enable (); } } void sgen_debug_dump_heap (const char *type, int num, const char *reason) { SgenPointerQueue *pinned_objects; int i; if (!heap_dump_file) return; fprintf (heap_dump_file, "<collection type=\"%s\" num=\"%d\"", type, num); if (reason) fprintf (heap_dump_file, " reason=\"%s\"", reason); fprintf (heap_dump_file, ">\n"); #ifndef SGEN_WITHOUT_MONO fprintf (heap_dump_file, "<other-mem-usage type=\"mempools\" size=\"%ld\"/>\n", mono_mempool_get_bytes_allocated ()); #endif sgen_dump_internal_mem_usage (heap_dump_file); fprintf (heap_dump_file, "<pinned type=\"stack\" bytes=\"%lu\"/>\n", (unsigned long)sgen_pin_stats_get_pinned_byte_count (PIN_TYPE_STACK)); /* fprintf (heap_dump_file, "<pinned type=\"static-data\" bytes=\"%d\"/>\n", pinned_byte_counts [PIN_TYPE_STATIC_DATA]); */ fprintf (heap_dump_file, "<pinned type=\"other\" bytes=\"%lu\"/>\n", (unsigned long)sgen_pin_stats_get_pinned_byte_count (PIN_TYPE_OTHER)); fprintf (heap_dump_file, "<pinned-objects>\n"); pinned_objects = sgen_pin_stats_get_object_list (); for (i = 0; i < pinned_objects->next_slot; ++i) dump_object ((GCObject *)pinned_objects->data [i], TRUE); fprintf (heap_dump_file, "</pinned-objects>\n"); sgen_dump_section (sgen_nursery_section, "nursery"); sgen_major_collector.dump_heap (heap_dump_file); fprintf (heap_dump_file, "<los>\n"); sgen_los_iterate_objects ((IterateObjectCallbackFunc)dump_object_callback, (void*)FALSE); fprintf (heap_dump_file, "</los>\n"); fprintf (heap_dump_file, "</collection>\n"); } static GCObject *found_obj; static void find_object_for_ptr_callback (GCObject *obj, size_t size, void *user_data) { char *ptr = (char *)user_data; if (ptr >= (char*)obj && ptr < (char*)obj + size) { g_assert (!found_obj); found_obj = obj; } } /* for use in the debugger */ GCObject* sgen_find_object_for_ptr (char *ptr) { if (ptr >= sgen_nursery_section->data && ptr < sgen_nursery_section->end_data) { found_obj = NULL; sgen_scan_area_with_callback (sgen_nursery_section->data, sgen_nursery_section->end_data, find_object_for_ptr_callback, ptr, TRUE, FALSE); if (found_obj) return found_obj; } found_obj = NULL; sgen_los_iterate_objects (find_object_for_ptr_callback, ptr); if (found_obj) return found_obj; /* * Very inefficient, but this is debugging code, supposed to * be called from gdb, so we don't care. */ found_obj = NULL; sgen_major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_ALL, find_object_for_ptr_callback, ptr); return found_obj; } #else void sgen_check_for_xdomain_refs (void) { } void sgen_check_heap_marked (gboolean nursery_must_be_pinned) { } void sgen_check_major_refs (void) { } void sgen_check_mod_union_consistency (void) { } void sgen_check_nursery_objects_untag (void) { } void sgen_check_remset_consistency (void) { } void sgen_check_whole_heap (gboolean allow_missing_pinned) { } void sgen_debug_check_nursery_is_clean (void) { } void sgen_debug_dump_heap (const char *type, int num, const char *reason) { } void sgen_debug_enable_heap_dump (const char *filename) { } void sgen_debug_verify_nursery (gboolean do_dump_nursery_content) { } void sgen_dump_occupied (char *start, char *end, char *section_start) { } void sgen_scan_for_registered_roots_in_domain (MonoDomain *domain, int root_type) { } #endif /*DISABLE_SGEN_DEBUG_HELPERS */ #endif /*HAVE_SGEN_GC*/
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/native/external/rapidjson/filereadstream.h
// Tencent is pleased to support the open source community by making RapidJSON available. // // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. // // Licensed under the MIT License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://opensource.org/licenses/MIT // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #ifndef RAPIDJSON_FILEREADSTREAM_H_ #define RAPIDJSON_FILEREADSTREAM_H_ #include "stream.h" #include <cstdio> #ifdef __clang__ RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(padded) RAPIDJSON_DIAG_OFF(unreachable-code) RAPIDJSON_DIAG_OFF(missing-noreturn) #endif RAPIDJSON_NAMESPACE_BEGIN //! File byte stream for input using fread(). /*! \note implements Stream concept */ class FileReadStream { public: typedef char Ch; //!< Character type (byte). //! Constructor. /*! \param fp File pointer opened for read. \param buffer user-supplied buffer. \param bufferSize size of buffer in bytes. Must >=4 bytes. */ FileReadStream(std::FILE* fp, char* buffer, size_t bufferSize) : fp_(fp), buffer_(buffer), bufferSize_(bufferSize), bufferLast_(0), current_(buffer_), readCount_(0), count_(0), eof_(false) { RAPIDJSON_ASSERT(fp_ != 0); RAPIDJSON_ASSERT(bufferSize >= 4); Read(); } Ch Peek() const { return *current_; } Ch Take() { Ch c = *current_; Read(); return c; } size_t Tell() const { return count_ + static_cast<size_t>(current_ - buffer_); } // Not implemented void Put(Ch) { RAPIDJSON_ASSERT(false); } void Flush() { RAPIDJSON_ASSERT(false); } Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; } // For encoding detection only. const Ch* Peek4() const { return (current_ + 4 - !eof_ <= bufferLast_) ? current_ : 0; } private: void Read() { if (current_ < bufferLast_) ++current_; else if (!eof_) { count_ += readCount_; readCount_ = std::fread(buffer_, 1, bufferSize_, fp_); bufferLast_ = buffer_ + readCount_ - 1; current_ = buffer_; if (readCount_ < bufferSize_) { buffer_[readCount_] = '\0'; ++bufferLast_; eof_ = true; } } } std::FILE* fp_; Ch *buffer_; size_t bufferSize_; Ch *bufferLast_; Ch *current_; size_t readCount_; size_t count_; //!< Number of characters read bool eof_; }; RAPIDJSON_NAMESPACE_END #ifdef __clang__ RAPIDJSON_DIAG_POP #endif #endif // RAPIDJSON_FILESTREAM_H_
// Tencent is pleased to support the open source community by making RapidJSON available. // // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. // // Licensed under the MIT License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://opensource.org/licenses/MIT // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #ifndef RAPIDJSON_FILEREADSTREAM_H_ #define RAPIDJSON_FILEREADSTREAM_H_ #include "stream.h" #include <cstdio> #ifdef __clang__ RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(padded) RAPIDJSON_DIAG_OFF(unreachable-code) RAPIDJSON_DIAG_OFF(missing-noreturn) #endif RAPIDJSON_NAMESPACE_BEGIN //! File byte stream for input using fread(). /*! \note implements Stream concept */ class FileReadStream { public: typedef char Ch; //!< Character type (byte). //! Constructor. /*! \param fp File pointer opened for read. \param buffer user-supplied buffer. \param bufferSize size of buffer in bytes. Must >=4 bytes. */ FileReadStream(std::FILE* fp, char* buffer, size_t bufferSize) : fp_(fp), buffer_(buffer), bufferSize_(bufferSize), bufferLast_(0), current_(buffer_), readCount_(0), count_(0), eof_(false) { RAPIDJSON_ASSERT(fp_ != 0); RAPIDJSON_ASSERT(bufferSize >= 4); Read(); } Ch Peek() const { return *current_; } Ch Take() { Ch c = *current_; Read(); return c; } size_t Tell() const { return count_ + static_cast<size_t>(current_ - buffer_); } // Not implemented void Put(Ch) { RAPIDJSON_ASSERT(false); } void Flush() { RAPIDJSON_ASSERT(false); } Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; } // For encoding detection only. const Ch* Peek4() const { return (current_ + 4 - !eof_ <= bufferLast_) ? current_ : 0; } private: void Read() { if (current_ < bufferLast_) ++current_; else if (!eof_) { count_ += readCount_; readCount_ = std::fread(buffer_, 1, bufferSize_, fp_); bufferLast_ = buffer_ + readCount_ - 1; current_ = buffer_; if (readCount_ < bufferSize_) { buffer_[readCount_] = '\0'; ++bufferLast_; eof_ = true; } } } std::FILE* fp_; Ch *buffer_; size_t bufferSize_; Ch *bufferLast_; Ch *current_; size_t readCount_; size_t count_; //!< Number of characters read bool eof_; }; RAPIDJSON_NAMESPACE_END #ifdef __clang__ RAPIDJSON_DIAG_POP #endif #endif // RAPIDJSON_FILESTREAM_H_
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/tools/superpmi/superpmi/cycletimer.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #ifndef _CycleTimer #define _CycleTimer #include "errorhandling.h" class CycleTimer { public: CycleTimer(); ~CycleTimer(); void Start(); void Stop(); unsigned __int64 GetCycles(); unsigned __int64 QueryOverhead(); private: // Cycles unsigned __int64 start; unsigned __int64 stop; unsigned __int64 overhead; }; #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #ifndef _CycleTimer #define _CycleTimer #include "errorhandling.h" class CycleTimer { public: CycleTimer(); ~CycleTimer(); void Start(); void Stop(); unsigned __int64 GetCycles(); unsigned __int64 QueryOverhead(); private: // Cycles unsigned __int64 start; unsigned __int64 stop; unsigned __int64 overhead; }; #endif
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/mono/mono/mini/mini-runtime.h
/** * \file * * Runtime declarations for the JIT. * * Copyright 2002-2003 Ximian Inc * Copyright 2003-2011 Novell Inc * Copyright 2011 Xamarin Inc * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #ifndef __MONO_MINI_RUNTIME_H__ #define __MONO_MINI_RUNTIME_H__ #include "mini.h" #include "ee.h" /* * Per-memory manager information maintained by the JIT. */ typedef struct { MonoMemoryManager *mem_manager; /* Maps MonoMethod's to a GSList of GOT slot addresses pointing to its code */ GHashTable *jump_target_got_slot_hash; GHashTable *jump_target_hash; /* Maps methods/klasses to the address of the given type of trampoline */ GHashTable *jump_trampoline_hash; GHashTable *jit_trampoline_hash; GHashTable *delegate_trampoline_hash; /* Maps ClassMethodPair -> MonoDelegateTrampInfo */ GHashTable *static_rgctx_trampoline_hash; /* maps MonoMethod -> MonoJitDynamicMethodInfo */ GHashTable *dynamic_code_hash; GHashTable *method_code_hash; /* Maps methods to a RuntimeInvokeInfo structure, protected by the associated MonoDomain lock */ MonoConcurrentHashTable *runtime_invoke_hash; /* Maps MonoMethod to a GPtrArray containing sequence point locations */ /* Protected by the domain lock */ GHashTable *seq_points; /* Debugger agent data */ gpointer agent_info; /* Maps MonoMethod to an arch-specific structure */ GHashTable *arch_seq_points; /* Maps a GSharedVtTrampInfo structure to a trampoline address */ GHashTable *gsharedvt_arg_tramp_hash; /* memcpy/bzero methods specialized for small constant sizes */ gpointer *memcpy_addr [17]; gpointer *bzero_addr [17]; gpointer llvm_module; /* Maps MonoMethod -> GSlist of addresses */ GHashTable *llvm_jit_callees; /* Maps MonoMethod -> RuntimeMethod */ MonoInternalHashTable interp_code_hash; /* Maps MonoMethod -> MonoMethodRuntimeGenericContext */ GHashTable *mrgctx_hash; GHashTable *method_rgctx_hash; /* Maps gpointer -> InterpMethod */ GHashTable *interp_method_pointer_hash; /* Protected by 'jit_code_hash_lock' */ MonoInternalHashTable jit_code_hash; mono_mutex_t jit_code_hash_lock; } MonoJitMemoryManager; static inline MonoJitMemoryManager* get_default_jit_mm (void) { return (MonoJitMemoryManager*)(mono_mem_manager_get_ambient ())->runtime_info; } // FIXME: Review uses and change them to a more specific mem manager static inline MonoMemoryManager* get_default_mem_manager (void) { return get_default_jit_mm ()->mem_manager; } static inline MonoJitMemoryManager* jit_mm_for_method (MonoMethod *method) { return (MonoJitMemoryManager*)m_method_get_mem_manager (method)->runtime_info; } static inline MonoJitMemoryManager* jit_mm_for_class (MonoClass *klass) { return (MonoJitMemoryManager*)m_class_get_mem_manager (klass)->runtime_info; } static inline void jit_mm_lock (MonoJitMemoryManager *jit_mm) { mono_mem_manager_lock (jit_mm->mem_manager); } static inline void jit_mm_unlock (MonoJitMemoryManager *jit_mm) { mono_mem_manager_unlock (jit_mm->mem_manager); } static inline void jit_code_hash_lock (MonoJitMemoryManager *jit_mm) { mono_locks_os_acquire(&(jit_mm)->jit_code_hash_lock, DomainJitCodeHashLock); } static inline void jit_code_hash_unlock (MonoJitMemoryManager *jit_mm) { mono_locks_os_release(&(jit_mm)->jit_code_hash_lock, DomainJitCodeHashLock); } /* Per vtable data maintained by the EE */ typedef struct { /* interp virtual method table */ gpointer *interp_vtable; MonoFtnDesc **gsharedvt_vtable; } MonoVTableEEData; /* * Stores state need to resume exception handling when using LLVM */ typedef struct { MonoJitInfo *ji; int clause_index; MonoContext ctx, new_ctx; /* FIXME: GC */ gpointer ex_obj; MonoLMF *lmf; int first_filter_idx, filter_idx; /* MonoMethodILState */ gpointer il_state; } ResumeState; typedef void (*MonoAbortFunction)(MonoObject*); struct MonoJitTlsData { gpointer end_of_stack; guint32 stack_size; MonoLMF *lmf; MonoLMF *first_lmf; guint handling_stack_ovf : 1; gpointer signal_stack; guint32 signal_stack_size; gpointer stack_ovf_guard_base; guint32 stack_ovf_guard_size; guint stack_ovf_valloced : 1; guint stack_ovf_pending : 1; MonoAbortFunction abort_func; /* Used to implement --debug=casts */ MonoClass *class_cast_from, *class_cast_to; /* Stores state needed by handler block with a guard */ MonoContext ex_ctx; ResumeState resume_state; /* handler block been guarded. It's safe to store this even for dynamic methods since there is an activation on stack making sure it will remain alive.*/ MonoJitExceptionInfo *handler_block; /* context to be used by the guard trampoline when resuming interruption.*/ MonoContext handler_block_context; /* * Stores the state at the exception throw site to be used by mono_stack_walk () * when it is called from profiler functions during exception handling. */ MonoContext orig_ex_ctx; gboolean orig_ex_ctx_set; /* * The current exception in flight */ MonoGCHandle thrown_exc; /* * If the current exception is not a subclass of Exception, * the original exception. */ MonoGCHandle thrown_non_exc; /* * The calling assembly in llvmonly mode. */ MonoImage *calling_image; /* * The stack frame "high water mark" for ThreadAbortExceptions. * We will rethrow the exception upon exiting a catch clause that's * in a function stack frame above the water mark(isn't being called by * the catch block that caught the ThreadAbortException). */ gpointer abort_exc_stack_threshold; /* * List of methods being JIT'd in the current thread. */ int active_jit_methods; gpointer interp_context; #if defined(TARGET_WIN32) MonoContext stack_restore_ctx; #endif }; typedef struct { MonoMethod *method; /* Either the IL offset of the currently executing code, or -1 */ int il_offset; /* For every arg+local, either its address on the stack, or NULL */ gpointer data [1]; } MonoMethodILState; #define MONO_LMFEXT_DEBUGGER_INVOKE 1 #define MONO_LMFEXT_INTERP_EXIT 2 #define MONO_LMFEXT_INTERP_EXIT_WITH_CTX 3 #define MONO_LMFEXT_JIT_ENTRY 4 #define MONO_LMFEXT_IL_STATE 5 /* * The MonoLMF structure is arch specific, it includes at least these fields. * LMF means 'last-managed-frame'. Originally, these were allocated * on the stack to mark the last frame before transitioning to * native code, but currently, they are used to mark all kinds of * other transitions as well, see MonoLMFExt. */ #if 0 typedef struct { /* * If the second lowest bit is set to 1, then this is a MonoLMFExt structure, and * the other fields are not valid. */ gpointer previous_lmf; gpointer lmf_addr; } MonoLMF; #endif /* * This structure is an extension of MonoLMF and contains extra information. */ typedef struct { struct MonoLMF lmf; int kind; MonoContext ctx; /* valid if kind == DEBUGGER_INVOKE || kind == INTERP_EXIT_WITH_CTX */ gpointer interp_exit_data; /* valid if kind == INTERP_EXIT || kind == INTERP_EXIT_WITH_CTX */ MonoMethodILState *il_state; /* valid if kind == IL_STATE */ #if defined (_MSC_VER) gboolean interp_exit_label_set; #endif } MonoLMFExt; typedef void (*MonoFtnPtrEHCallback) (MonoGCHandle gchandle); typedef struct MonoDebugOptions { gboolean handle_sigint; gboolean keep_delegates; gboolean reverse_pinvoke_exceptions; gboolean collect_pagefault_stats; gboolean break_on_unverified; gboolean better_cast_details; gboolean mdb_optimizations; gboolean no_gdb_backtrace; gboolean suspend_on_native_crash; gboolean suspend_on_exception; gboolean suspend_on_unhandled; gboolean dyn_runtime_invoke; gboolean lldb; /* * Prevent LLVM from inlining any methods */ gboolean llvm_disable_inlining; gboolean llvm_disable_implicit_null_checks; gboolean use_fallback_tls; /* * Whenever data such as next sequence points and flags is required. * Next sequence points and flags are required by the debugger agent. */ gboolean gen_sdb_seq_points; gboolean no_seq_points_compact_data; /* * Setting single_imm_size should guarantee that each time managed code is compiled * the same instructions and registers are used, regardless of the size of used values. */ gboolean single_imm_size; gboolean explicit_null_checks; /* * Fill stack frames with 0x2a in method prologs. This helps with the * debugging of the stack marking code in the GC. */ gboolean init_stacks; /* * Whenever to implement single stepping and breakpoints without signals in the * soft debugger. This is useful on platforms without signals, like the ps3, or during * runtime debugging, since it avoids SIGSEGVs when a single step location or breakpoint * is hit. */ gboolean soft_breakpoints; /* * Whenever to break in the debugger using G_BREAKPOINT on unhandled exceptions. */ gboolean break_on_exc; /* * Load AOT JIT info eagerly. */ gboolean load_aot_jit_info_eagerly; /* * Check for pinvoke calling convention mismatches. */ gboolean check_pinvoke_callconv; /* * Translate Debugger.Break () into a native breakpoint signal */ gboolean native_debugger_break; /* * Disabling the frame pointer emit optimization can allow debuggers to more easily * identify the stack on some platforms */ gboolean disable_omit_fp; /* * Make gdb output on native crashes more verbose. */ gboolean verbose_gdb; // Internal testing feature. gboolean test_tailcall_require; /* * Don't enforce any memory model. We will assume the architecture's memory model. */ gboolean weak_memory_model; /* * Internal testing feature * Testing feature, skip loading the Nth aot loadable method. */ gboolean aot_skip_set; int aot_skip; /* * Treat exceptions which reach the topmost runtime invoke as unhandled when * embedding. */ gboolean top_runtime_invoke_unhandled; gboolean enabled; } MonoDebugOptions; /* * We need to store the image which the token refers to along with the token, * since the image might not be the same as the image of the method which * contains the relocation, because of inlining. */ typedef struct MonoJumpInfoToken { MonoImage *image; guint32 token; gboolean has_context; MonoGenericContext context; } MonoJumpInfoToken; typedef struct MonoJumpInfoBBTable { MonoBasicBlock **table; int table_size; } MonoJumpInfoBBTable; /* Contains information describing an LLVM IMT trampoline */ typedef struct MonoJumpInfoImtTramp { MonoMethod *method; int vt_offset; } MonoJumpInfoImtTramp; /* * Contains information for computing the * property given by INFO_TYPE of the runtime * object described by DATA. */ struct MonoJumpInfoRgctxEntry { union { /* If in_mrgctx is TRUE */ MonoMethod *method; /* If in_mrgctx is FALSE */ MonoClass *klass; } d; gboolean in_mrgctx; MonoJumpInfo *data; /* describes the data to be loaded */ MonoRgctxInfoType info_type; }; /* Contains information about a gsharedvt call */ struct MonoJumpInfoGSharedVtCall { /* The original signature of the call */ MonoMethodSignature *sig; /* The method which is called */ MonoMethod *method; }; /* * Represents the method which is called when a virtual call is made to METHOD * on a receiver of type KLASS. */ typedef struct { /* Receiver class */ MonoClass *klass; /* Virtual method */ MonoMethod *method; } MonoJumpInfoVirtMethod; struct MonoJumpInfo { MonoJumpInfo *next; /* Relocation type for patching */ int relocation; union { int i; guint8 *p; MonoInst *label; } ip; MonoJumpInfoType type; union { // In order to allow blindly using target in mono_add_patch_info, // all fields must be pointer-sized. No ints, no untyped enums. gconstpointer target; gssize index; // only 32 bits used but widened per above gsize uindex; // only 32 bits used but widened per above MonoBasicBlock *bb; MonoInst *inst; MonoMethod *method; MonoClass *klass; MonoClassField *field; MonoImage *image; MonoVTable *vtable; const char *name; gsize jit_icall_id; // MonoJitICallId, 9 bits, but widened per above. MonoJumpInfoToken *token; MonoJumpInfoBBTable *table; MonoJumpInfoRgctxEntry *rgctx_entry; MonoJumpInfoImtTramp *imt_tramp; MonoJumpInfoGSharedVtCall *gsharedvt; MonoGSharedVtMethodInfo *gsharedvt_method; MonoMethodSignature *sig; MonoDelegateClassMethodPair *del_tramp; /* MONO_PATCH_INFO_VIRT_METHOD */ MonoJumpInfoVirtMethod *virt_method; } data; }; extern gboolean mono_break_on_exc; extern gboolean mono_compile_aot; extern gboolean mono_aot_only; extern gboolean mono_llvm_only; extern MonoAotMode mono_aot_mode; MONO_BEGIN_DECLS MONO_API_DATA const char *mono_build_date; MONO_END_DECLS extern gboolean mono_do_signal_chaining; extern gboolean mono_do_crash_chaining; MONO_BEGIN_DECLS MONO_API_DATA gboolean mono_use_llvm; MONO_API_DATA gboolean mono_use_fast_math; MONO_API_DATA gboolean mono_use_interpreter; MONO_API_DATA MonoCPUFeatures mono_cpu_features_enabled; MONO_API_DATA MonoCPUFeatures mono_cpu_features_disabled; MONO_END_DECLS extern const char* mono_interp_opts_string; extern gboolean mono_do_single_method_regression; extern guint32 mono_single_method_regression_opt; extern MonoMethod *mono_current_single_method; extern GSList *mono_single_method_list; extern GHashTable *mono_single_method_hash; extern GList* mono_aot_paths; extern MonoDebugOptions mini_debug_options; extern GSList *mono_interp_only_classes; extern MonoMethodDesc *mono_stats_method_desc; MONO_COMPONENT_API MonoDebugOptions *get_mini_debug_options (void); /* This struct describes what execution engine feature to use. This subsume, and will eventually sunset, mono_aot_only / mono_llvm_only and friends. The goal is to transition us to a place were we can more easily compose/describe what features we need for a given execution mode. A good feature flag is checked alone, a bad one described many things and keeps breaking some of the modes */ typedef struct { /* * If true, trampolines are to be fetched from the AOT runtime instead of JIT compiled */ gboolean use_aot_trampolines; /* * If true, the runtime will try to use the interpreter before looking for compiled code. */ gboolean force_use_interpreter; } MonoEEFeatures; extern MonoEEFeatures mono_ee_features; //XXX this enum *MUST extend MonoAotMode as they are consumed together. typedef enum { MONO_EE_MODE_INTERP = MONO_AOT_MODE_INTERP_ONLY, } MonoEEMode; static inline MonoMethod* jinfo_get_method (MonoJitInfo *ji) { return mono_jit_info_get_method (ji); } static inline gpointer jinfo_get_ftnptr (MonoJitInfo *ji) { return MINI_ADDR_TO_FTNPTR (ji->code_start); } /* main function */ MONO_API int mono_main (int argc, char* argv[]); MONO_API void mono_set_defaults (int verbose_level, guint32 opts); MONO_API void mono_parse_env_options (int *ref_argc, char **ref_argv []); MONO_API char *mono_parse_options_from (const char *options, int *ref_argc, char **ref_argv []); MONO_API int mono_regression_test_step (int verbose_level, const char *image, const char *method_name); void mono_runtime_print_stats (void); void mono_interp_stub_init (void); void mini_install_interp_callbacks (const MonoEECallbacks *cbs); extern const MonoEECallbacks* mono_interp_callbacks_pointer; #define mini_get_interp_callbacks() (mono_interp_callbacks_pointer) MONO_COMPONENT_API const MonoEECallbacks* mini_get_interp_callbacks_api (void); MonoDomain* mini_init (const char *filename, const char *runtime_version); void mini_cleanup (MonoDomain *domain); MONO_API MonoDebugOptions *mini_get_debug_options (void); MONO_API gboolean mini_parse_debug_option (const char *option); MONO_API void mono_install_ftnptr_eh_callback (MonoFtnPtrEHCallback callback); void mini_jit_init (void); void mono_disable_optimizations (guint32 opts); void mono_set_optimizations (guint32 opts); void mono_precompile_assemblies (void); MONO_API int mono_parse_default_optimizations (const char* p); gboolean mono_running_on_valgrind (void); MONO_COMPONENT_API MonoLMF * mono_get_lmf (void); void mono_set_lmf (MonoLMF *lmf); MONO_COMPONENT_API void mono_push_lmf (MonoLMFExt *ext); MONO_COMPONENT_API void mono_pop_lmf (MonoLMF *lmf); MONO_API MONO_RT_EXTERNAL_ONLY void mono_jit_set_domain (MonoDomain *domain); gboolean mono_method_same_domain (MonoJitInfo *caller, MonoJitInfo *callee); gpointer mono_create_ftnptr (gpointer addr); MonoMethod* mono_icall_get_wrapper_method (MonoJitICallInfo* callinfo); gconstpointer mono_icall_get_wrapper (MonoJitICallInfo* callinfo); gconstpointer mono_icall_get_wrapper_full (MonoJitICallInfo* callinfo, gboolean do_compile); MonoJumpInfo* mono_patch_info_dup_mp (MonoMemPool *mp, MonoJumpInfo *patch_info); guint mono_patch_info_hash (gconstpointer data); gint mono_patch_info_equal (gconstpointer ka, gconstpointer kb); MonoJumpInfo *mono_patch_info_list_prepend (MonoJumpInfo *list, int ip, MonoJumpInfoType type, gconstpointer target); MonoJumpInfoToken* mono_jump_info_token_new (MonoMemPool *mp, MonoImage *image, guint32 token); MonoJumpInfoToken* mono_jump_info_token_new2 (MonoMemPool *mp, MonoImage *image, guint32 token, MonoGenericContext *context); gpointer mono_resolve_patch_target (MonoMethod *method, guint8 *code, MonoJumpInfo *patch_info, gboolean run_cctors, MonoError *error); gpointer mono_resolve_patch_target_ext (MonoMemoryManager *mem_manager, MonoMethod *method, guint8 *code, MonoJumpInfo *patch_info, gboolean run_cctors, MonoError *error); void mini_register_jump_site (MonoMethod *method, gpointer ip); void mini_patch_jump_sites (MonoMethod *method, gpointer addr); void mini_patch_llvm_jit_callees (MonoMethod *method, gpointer addr); MONO_COMPONENT_API gpointer mono_jit_search_all_backends_for_jit_info (MonoMethod *method, MonoJitInfo **ji); gpointer mono_jit_find_compiled_method_with_jit_info (MonoMethod *method, MonoJitInfo **ji); gpointer mono_jit_find_compiled_method (MonoMethod *method); gpointer mono_jit_compile_method (MonoMethod *method, MonoError *error); gpointer mono_jit_compile_method_jit_only (MonoMethod *method, MonoError *error); void mono_set_bisect_methods (guint32 opt, const char *method_list_filename); guint32 mono_get_optimizations_for_method (MonoMethod *method, guint32 default_opt); char* mono_opt_descr (guint32 flags); void mono_set_verbose_level (guint32 level); const char*mono_ji_type_to_string (MonoJumpInfoType type); void mono_print_ji (const MonoJumpInfo *ji); MONO_API void mono_print_method_from_ip (void *ip); MONO_API char *mono_pmip (void *ip); MONO_API char *mono_pmip_u (void *ip); MONO_API int mono_ee_api_version (void); gboolean mono_debug_count (void); #ifdef __linux__ /* maybe enable also for other systems? */ #define ENABLE_JIT_MAP 1 void mono_enable_jit_map (void); void mono_emit_jit_map (MonoJitInfo *jinfo); void mono_emit_jit_tramp (void *start, int size, const char *desc); gboolean mono_jit_map_is_enabled (void); #else #define mono_enable_jit_map() #define mono_emit_jit_map(ji) #define mono_emit_jit_tramp(s,z,d) do { } while (0) /* non-empty to avoid warning */ #define mono_jit_map_is_enabled() (0) #endif void mono_enable_jit_dump (void); void mono_emit_jit_dump (MonoJitInfo *jinfo, gpointer code); void mono_jit_dump_cleanup (void); gpointer mini_alloc_generic_virtual_trampoline (MonoVTable *vtable, int size); MonoException* mini_get_stack_overflow_ex (void); /* * Per-OS implementation functions. */ void mono_runtime_install_handlers (void); gboolean mono_runtime_install_custom_handlers (const char *handlers); void mono_runtime_install_custom_handlers_usage (void); void mono_runtime_setup_stat_profiler (void); void mono_runtime_posix_install_handlers (void); void mono_gdb_render_native_backtraces (pid_t crashed_pid); void mono_cross_helpers_run (void); void mono_init_native_crash_info (void); void mono_dump_native_crash_info (const char *signal, MonoContext *mctx, MONO_SIG_HANDLER_INFO_TYPE *info); void mono_post_native_crash_handler (const char *signal, MonoContext *mctx, MONO_SIG_HANDLER_INFO_TYPE *info, gboolean crash_chaining); gboolean mono_is_addr_implicit_null_check (void *addr); /* * Signal handling */ #if defined(DISABLE_HW_TRAPS) || defined(MONO_ARCH_DISABLE_HW_TRAPS) // Signal handlers not available #define MONO_ARCH_NEED_DIV_CHECK 1 #endif void MONO_SIG_HANDLER_SIGNATURE (mono_sigfpe_signal_handler) ; void MONO_SIG_HANDLER_SIGNATURE (mono_crashing_signal_handler) ; void MONO_SIG_HANDLER_SIGNATURE (mono_sigsegv_signal_handler); void MONO_SIG_HANDLER_SIGNATURE (mono_sigint_signal_handler) ; gboolean MONO_SIG_HANDLER_SIGNATURE (mono_chain_signal); #if defined (HOST_WASM) #define MONO_RETURN_ADDRESS_N(N) NULL #define MONO_RETURN_ADDRESS() MONO_RETURN_ADDRESS_N(0) #elif defined (__GNUC__) #define MONO_RETURN_ADDRESS_N(N) (__builtin_extract_return_addr (__builtin_return_address (N))) #define MONO_RETURN_ADDRESS() MONO_RETURN_ADDRESS_N(0) #elif defined(_MSC_VER) #include <intrin.h> #pragma intrinsic(_ReturnAddress) #define MONO_RETURN_ADDRESS() _ReturnAddress() #define MONO_RETURN_ADDRESS_N(N) NULL #else #error "Missing return address intrinsics implementation" #endif //have a global view of sdb disable #if !defined(MONO_ARCH_SOFT_DEBUG_SUPPORTED) || defined (DISABLE_DEBUGGER_AGENT) #define DISABLE_SDB 1 #endif void mini_register_sigterm_handler (void); #define MINI_BEGIN_CODEGEN() do { \ mono_codeman_enable_write (); \ } while (0) #define MINI_END_CODEGEN(buf,size,type,arg) do { \ mono_codeman_disable_write (); \ mono_arch_flush_icache ((buf), (size)); \ if ((int)type != -1) \ MONO_PROFILER_RAISE (jit_code_buffer, ((buf), (size), (MonoProfilerCodeBufferType)(type), (arg))); \ } while (0) #endif /* __MONO_MINI_RUNTIME_H__ */
/** * \file * * Runtime declarations for the JIT. * * Copyright 2002-2003 Ximian Inc * Copyright 2003-2011 Novell Inc * Copyright 2011 Xamarin Inc * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #ifndef __MONO_MINI_RUNTIME_H__ #define __MONO_MINI_RUNTIME_H__ #include "mini.h" #include "ee.h" /* * Per-memory manager information maintained by the JIT. */ typedef struct { MonoMemoryManager *mem_manager; /* Maps MonoMethod's to a GSList of GOT slot addresses pointing to its code */ GHashTable *jump_target_got_slot_hash; GHashTable *jump_target_hash; /* Maps methods/klasses to the address of the given type of trampoline */ GHashTable *jump_trampoline_hash; GHashTable *jit_trampoline_hash; GHashTable *delegate_trampoline_hash; /* Maps ClassMethodPair -> MonoDelegateTrampInfo */ GHashTable *static_rgctx_trampoline_hash; /* maps MonoMethod -> MonoJitDynamicMethodInfo */ GHashTable *dynamic_code_hash; GHashTable *method_code_hash; /* Maps methods to a RuntimeInvokeInfo structure, protected by the associated MonoDomain lock */ MonoConcurrentHashTable *runtime_invoke_hash; /* Maps MonoMethod to a GPtrArray containing sequence point locations */ /* Protected by the domain lock */ GHashTable *seq_points; /* Debugger agent data */ gpointer agent_info; /* Maps MonoMethod to an arch-specific structure */ GHashTable *arch_seq_points; /* Maps a GSharedVtTrampInfo structure to a trampoline address */ GHashTable *gsharedvt_arg_tramp_hash; /* memcpy/bzero methods specialized for small constant sizes */ gpointer *memcpy_addr [17]; gpointer *bzero_addr [17]; gpointer llvm_module; /* Maps MonoMethod -> GSlist of addresses */ GHashTable *llvm_jit_callees; /* Maps MonoMethod -> RuntimeMethod */ MonoInternalHashTable interp_code_hash; /* Maps MonoMethod -> MonoMethodRuntimeGenericContext */ GHashTable *mrgctx_hash; GHashTable *method_rgctx_hash; /* Maps gpointer -> InterpMethod */ GHashTable *interp_method_pointer_hash; /* Protected by 'jit_code_hash_lock' */ MonoInternalHashTable jit_code_hash; mono_mutex_t jit_code_hash_lock; } MonoJitMemoryManager; static inline MonoJitMemoryManager* get_default_jit_mm (void) { return (MonoJitMemoryManager*)(mono_mem_manager_get_ambient ())->runtime_info; } // FIXME: Review uses and change them to a more specific mem manager static inline MonoMemoryManager* get_default_mem_manager (void) { return get_default_jit_mm ()->mem_manager; } static inline MonoJitMemoryManager* jit_mm_for_method (MonoMethod *method) { return (MonoJitMemoryManager*)m_method_get_mem_manager (method)->runtime_info; } static inline MonoJitMemoryManager* jit_mm_for_class (MonoClass *klass) { return (MonoJitMemoryManager*)m_class_get_mem_manager (klass)->runtime_info; } static inline void jit_mm_lock (MonoJitMemoryManager *jit_mm) { mono_mem_manager_lock (jit_mm->mem_manager); } static inline void jit_mm_unlock (MonoJitMemoryManager *jit_mm) { mono_mem_manager_unlock (jit_mm->mem_manager); } static inline void jit_code_hash_lock (MonoJitMemoryManager *jit_mm) { mono_locks_os_acquire(&(jit_mm)->jit_code_hash_lock, DomainJitCodeHashLock); } static inline void jit_code_hash_unlock (MonoJitMemoryManager *jit_mm) { mono_locks_os_release(&(jit_mm)->jit_code_hash_lock, DomainJitCodeHashLock); } /* Per vtable data maintained by the EE */ typedef struct { /* interp virtual method table */ gpointer *interp_vtable; MonoFtnDesc **gsharedvt_vtable; } MonoVTableEEData; /* * Stores state need to resume exception handling when using LLVM */ typedef struct { MonoJitInfo *ji; int clause_index; MonoContext ctx, new_ctx; /* FIXME: GC */ gpointer ex_obj; MonoLMF *lmf; int first_filter_idx, filter_idx; /* MonoMethodILState */ gpointer il_state; } ResumeState; typedef void (*MonoAbortFunction)(MonoObject*); struct MonoJitTlsData { gpointer end_of_stack; guint32 stack_size; MonoLMF *lmf; MonoLMF *first_lmf; guint handling_stack_ovf : 1; gpointer signal_stack; guint32 signal_stack_size; gpointer stack_ovf_guard_base; guint32 stack_ovf_guard_size; guint stack_ovf_valloced : 1; guint stack_ovf_pending : 1; MonoAbortFunction abort_func; /* Used to implement --debug=casts */ MonoClass *class_cast_from, *class_cast_to; /* Stores state needed by handler block with a guard */ MonoContext ex_ctx; ResumeState resume_state; /* handler block been guarded. It's safe to store this even for dynamic methods since there is an activation on stack making sure it will remain alive.*/ MonoJitExceptionInfo *handler_block; /* context to be used by the guard trampoline when resuming interruption.*/ MonoContext handler_block_context; /* * Stores the state at the exception throw site to be used by mono_stack_walk () * when it is called from profiler functions during exception handling. */ MonoContext orig_ex_ctx; gboolean orig_ex_ctx_set; /* * The current exception in flight */ MonoGCHandle thrown_exc; /* * If the current exception is not a subclass of Exception, * the original exception. */ MonoGCHandle thrown_non_exc; /* * The calling assembly in llvmonly mode. */ MonoImage *calling_image; /* * The stack frame "high water mark" for ThreadAbortExceptions. * We will rethrow the exception upon exiting a catch clause that's * in a function stack frame above the water mark(isn't being called by * the catch block that caught the ThreadAbortException). */ gpointer abort_exc_stack_threshold; /* * List of methods being JIT'd in the current thread. */ int active_jit_methods; gpointer interp_context; #if defined(TARGET_WIN32) MonoContext stack_restore_ctx; #endif }; typedef struct { MonoMethod *method; /* Either the IL offset of the currently executing code, or -1 */ int il_offset; /* For every arg+local, either its address on the stack, or NULL */ gpointer data [1]; } MonoMethodILState; #define MONO_LMFEXT_DEBUGGER_INVOKE 1 #define MONO_LMFEXT_INTERP_EXIT 2 #define MONO_LMFEXT_INTERP_EXIT_WITH_CTX 3 #define MONO_LMFEXT_JIT_ENTRY 4 #define MONO_LMFEXT_IL_STATE 5 /* * The MonoLMF structure is arch specific, it includes at least these fields. * LMF means 'last-managed-frame'. Originally, these were allocated * on the stack to mark the last frame before transitioning to * native code, but currently, they are used to mark all kinds of * other transitions as well, see MonoLMFExt. */ #if 0 typedef struct { /* * If the second lowest bit is set to 1, then this is a MonoLMFExt structure, and * the other fields are not valid. */ gpointer previous_lmf; gpointer lmf_addr; } MonoLMF; #endif /* * This structure is an extension of MonoLMF and contains extra information. */ typedef struct { struct MonoLMF lmf; int kind; MonoContext ctx; /* valid if kind == DEBUGGER_INVOKE || kind == INTERP_EXIT_WITH_CTX */ gpointer interp_exit_data; /* valid if kind == INTERP_EXIT || kind == INTERP_EXIT_WITH_CTX */ MonoMethodILState *il_state; /* valid if kind == IL_STATE */ #if defined (_MSC_VER) gboolean interp_exit_label_set; #endif } MonoLMFExt; typedef void (*MonoFtnPtrEHCallback) (MonoGCHandle gchandle); typedef struct MonoDebugOptions { gboolean handle_sigint; gboolean keep_delegates; gboolean reverse_pinvoke_exceptions; gboolean collect_pagefault_stats; gboolean break_on_unverified; gboolean better_cast_details; gboolean mdb_optimizations; gboolean no_gdb_backtrace; gboolean suspend_on_native_crash; gboolean suspend_on_exception; gboolean suspend_on_unhandled; gboolean dyn_runtime_invoke; gboolean lldb; /* * Prevent LLVM from inlining any methods */ gboolean llvm_disable_inlining; gboolean llvm_disable_implicit_null_checks; gboolean use_fallback_tls; /* * Whenever data such as next sequence points and flags is required. * Next sequence points and flags are required by the debugger agent. */ gboolean gen_sdb_seq_points; gboolean no_seq_points_compact_data; /* * Setting single_imm_size should guarantee that each time managed code is compiled * the same instructions and registers are used, regardless of the size of used values. */ gboolean single_imm_size; gboolean explicit_null_checks; /* * Fill stack frames with 0x2a in method prologs. This helps with the * debugging of the stack marking code in the GC. */ gboolean init_stacks; /* * Whenever to implement single stepping and breakpoints without signals in the * soft debugger. This is useful on platforms without signals, like the ps3, or during * runtime debugging, since it avoids SIGSEGVs when a single step location or breakpoint * is hit. */ gboolean soft_breakpoints; /* * Whenever to break in the debugger using G_BREAKPOINT on unhandled exceptions. */ gboolean break_on_exc; /* * Load AOT JIT info eagerly. */ gboolean load_aot_jit_info_eagerly; /* * Check for pinvoke calling convention mismatches. */ gboolean check_pinvoke_callconv; /* * Translate Debugger.Break () into a native breakpoint signal */ gboolean native_debugger_break; /* * Disabling the frame pointer emit optimization can allow debuggers to more easily * identify the stack on some platforms */ gboolean disable_omit_fp; /* * Make gdb output on native crashes more verbose. */ gboolean verbose_gdb; // Internal testing feature. gboolean test_tailcall_require; /* * Don't enforce any memory model. We will assume the architecture's memory model. */ gboolean weak_memory_model; /* * Internal testing feature * Testing feature, skip loading the Nth aot loadable method. */ gboolean aot_skip_set; int aot_skip; /* * Treat exceptions which reach the topmost runtime invoke as unhandled when * embedding. */ gboolean top_runtime_invoke_unhandled; gboolean enabled; } MonoDebugOptions; /* * We need to store the image which the token refers to along with the token, * since the image might not be the same as the image of the method which * contains the relocation, because of inlining. */ typedef struct MonoJumpInfoToken { MonoImage *image; guint32 token; gboolean has_context; MonoGenericContext context; } MonoJumpInfoToken; typedef struct MonoJumpInfoBBTable { MonoBasicBlock **table; int table_size; } MonoJumpInfoBBTable; /* Contains information describing an LLVM IMT trampoline */ typedef struct MonoJumpInfoImtTramp { MonoMethod *method; int vt_offset; } MonoJumpInfoImtTramp; /* * Contains information for computing the * property given by INFO_TYPE of the runtime * object described by DATA. */ struct MonoJumpInfoRgctxEntry { union { /* If in_mrgctx is TRUE */ MonoMethod *method; /* If in_mrgctx is FALSE */ MonoClass *klass; } d; gboolean in_mrgctx; MonoJumpInfo *data; /* describes the data to be loaded */ MonoRgctxInfoType info_type; }; /* Contains information about a gsharedvt call */ struct MonoJumpInfoGSharedVtCall { /* The original signature of the call */ MonoMethodSignature *sig; /* The method which is called */ MonoMethod *method; }; /* * Represents the method which is called when a virtual call is made to METHOD * on a receiver of type KLASS. */ typedef struct { /* Receiver class */ MonoClass *klass; /* Virtual method */ MonoMethod *method; } MonoJumpInfoVirtMethod; struct MonoJumpInfo { MonoJumpInfo *next; /* Relocation type for patching */ int relocation; union { int i; guint8 *p; MonoInst *label; } ip; MonoJumpInfoType type; union { // In order to allow blindly using target in mono_add_patch_info, // all fields must be pointer-sized. No ints, no untyped enums. gconstpointer target; gssize index; // only 32 bits used but widened per above gsize uindex; // only 32 bits used but widened per above MonoBasicBlock *bb; MonoInst *inst; MonoMethod *method; MonoClass *klass; MonoClassField *field; MonoImage *image; MonoVTable *vtable; const char *name; gsize jit_icall_id; // MonoJitICallId, 9 bits, but widened per above. MonoJumpInfoToken *token; MonoJumpInfoBBTable *table; MonoJumpInfoRgctxEntry *rgctx_entry; MonoJumpInfoImtTramp *imt_tramp; MonoJumpInfoGSharedVtCall *gsharedvt; MonoGSharedVtMethodInfo *gsharedvt_method; MonoMethodSignature *sig; MonoDelegateClassMethodPair *del_tramp; /* MONO_PATCH_INFO_VIRT_METHOD */ MonoJumpInfoVirtMethod *virt_method; } data; }; extern gboolean mono_break_on_exc; extern gboolean mono_compile_aot; extern gboolean mono_aot_only; extern gboolean mono_llvm_only; extern MonoAotMode mono_aot_mode; MONO_BEGIN_DECLS MONO_API_DATA const char *mono_build_date; MONO_END_DECLS extern gboolean mono_do_signal_chaining; extern gboolean mono_do_crash_chaining; MONO_BEGIN_DECLS MONO_API_DATA gboolean mono_use_llvm; MONO_API_DATA gboolean mono_use_fast_math; MONO_API_DATA gboolean mono_use_interpreter; MONO_API_DATA MonoCPUFeatures mono_cpu_features_enabled; MONO_API_DATA MonoCPUFeatures mono_cpu_features_disabled; MONO_END_DECLS extern const char* mono_interp_opts_string; extern gboolean mono_do_single_method_regression; extern guint32 mono_single_method_regression_opt; extern MonoMethod *mono_current_single_method; extern GSList *mono_single_method_list; extern GHashTable *mono_single_method_hash; extern GList* mono_aot_paths; extern MonoDebugOptions mini_debug_options; extern GSList *mono_interp_only_classes; extern MonoMethodDesc *mono_stats_method_desc; MONO_COMPONENT_API MonoDebugOptions *get_mini_debug_options (void); /* This struct describes what execution engine feature to use. This subsume, and will eventually sunset, mono_aot_only / mono_llvm_only and friends. The goal is to transition us to a place were we can more easily compose/describe what features we need for a given execution mode. A good feature flag is checked alone, a bad one described many things and keeps breaking some of the modes */ typedef struct { /* * If true, trampolines are to be fetched from the AOT runtime instead of JIT compiled */ gboolean use_aot_trampolines; /* * If true, the runtime will try to use the interpreter before looking for compiled code. */ gboolean force_use_interpreter; } MonoEEFeatures; extern MonoEEFeatures mono_ee_features; //XXX this enum *MUST extend MonoAotMode as they are consumed together. typedef enum { MONO_EE_MODE_INTERP = MONO_AOT_MODE_INTERP_ONLY, } MonoEEMode; static inline MonoMethod* jinfo_get_method (MonoJitInfo *ji) { return mono_jit_info_get_method (ji); } static inline gpointer jinfo_get_ftnptr (MonoJitInfo *ji) { return MINI_ADDR_TO_FTNPTR (ji->code_start); } /* main function */ MONO_API int mono_main (int argc, char* argv[]); MONO_API void mono_set_defaults (int verbose_level, guint32 opts); MONO_API void mono_parse_env_options (int *ref_argc, char **ref_argv []); MONO_API char *mono_parse_options_from (const char *options, int *ref_argc, char **ref_argv []); MONO_API int mono_regression_test_step (int verbose_level, const char *image, const char *method_name); void mono_runtime_print_stats (void); void mono_interp_stub_init (void); void mini_install_interp_callbacks (const MonoEECallbacks *cbs); extern const MonoEECallbacks* mono_interp_callbacks_pointer; #define mini_get_interp_callbacks() (mono_interp_callbacks_pointer) MONO_COMPONENT_API const MonoEECallbacks* mini_get_interp_callbacks_api (void); MonoDomain* mini_init (const char *filename, const char *runtime_version); void mini_cleanup (MonoDomain *domain); MONO_API MonoDebugOptions *mini_get_debug_options (void); MONO_API gboolean mini_parse_debug_option (const char *option); MONO_API void mono_install_ftnptr_eh_callback (MonoFtnPtrEHCallback callback); void mini_jit_init (void); void mono_disable_optimizations (guint32 opts); void mono_set_optimizations (guint32 opts); void mono_precompile_assemblies (void); MONO_API int mono_parse_default_optimizations (const char* p); gboolean mono_running_on_valgrind (void); MONO_COMPONENT_API MonoLMF * mono_get_lmf (void); void mono_set_lmf (MonoLMF *lmf); MONO_COMPONENT_API void mono_push_lmf (MonoLMFExt *ext); MONO_COMPONENT_API void mono_pop_lmf (MonoLMF *lmf); MONO_API MONO_RT_EXTERNAL_ONLY void mono_jit_set_domain (MonoDomain *domain); gboolean mono_method_same_domain (MonoJitInfo *caller, MonoJitInfo *callee); gpointer mono_create_ftnptr (gpointer addr); MonoMethod* mono_icall_get_wrapper_method (MonoJitICallInfo* callinfo); gconstpointer mono_icall_get_wrapper (MonoJitICallInfo* callinfo); gconstpointer mono_icall_get_wrapper_full (MonoJitICallInfo* callinfo, gboolean do_compile); MonoJumpInfo* mono_patch_info_dup_mp (MonoMemPool *mp, MonoJumpInfo *patch_info); guint mono_patch_info_hash (gconstpointer data); gint mono_patch_info_equal (gconstpointer ka, gconstpointer kb); MonoJumpInfo *mono_patch_info_list_prepend (MonoJumpInfo *list, int ip, MonoJumpInfoType type, gconstpointer target); MonoJumpInfoToken* mono_jump_info_token_new (MonoMemPool *mp, MonoImage *image, guint32 token); MonoJumpInfoToken* mono_jump_info_token_new2 (MonoMemPool *mp, MonoImage *image, guint32 token, MonoGenericContext *context); gpointer mono_resolve_patch_target (MonoMethod *method, guint8 *code, MonoJumpInfo *patch_info, gboolean run_cctors, MonoError *error); gpointer mono_resolve_patch_target_ext (MonoMemoryManager *mem_manager, MonoMethod *method, guint8 *code, MonoJumpInfo *patch_info, gboolean run_cctors, MonoError *error); void mini_register_jump_site (MonoMethod *method, gpointer ip); void mini_patch_jump_sites (MonoMethod *method, gpointer addr); void mini_patch_llvm_jit_callees (MonoMethod *method, gpointer addr); MONO_COMPONENT_API gpointer mono_jit_search_all_backends_for_jit_info (MonoMethod *method, MonoJitInfo **ji); gpointer mono_jit_find_compiled_method_with_jit_info (MonoMethod *method, MonoJitInfo **ji); gpointer mono_jit_find_compiled_method (MonoMethod *method); gpointer mono_jit_compile_method (MonoMethod *method, MonoError *error); gpointer mono_jit_compile_method_jit_only (MonoMethod *method, MonoError *error); void mono_set_bisect_methods (guint32 opt, const char *method_list_filename); guint32 mono_get_optimizations_for_method (MonoMethod *method, guint32 default_opt); char* mono_opt_descr (guint32 flags); void mono_set_verbose_level (guint32 level); const char*mono_ji_type_to_string (MonoJumpInfoType type); void mono_print_ji (const MonoJumpInfo *ji); MONO_API void mono_print_method_from_ip (void *ip); MONO_API char *mono_pmip (void *ip); MONO_API char *mono_pmip_u (void *ip); MONO_API int mono_ee_api_version (void); gboolean mono_debug_count (void); #ifdef __linux__ /* maybe enable also for other systems? */ #define ENABLE_JIT_MAP 1 void mono_enable_jit_map (void); void mono_emit_jit_map (MonoJitInfo *jinfo); void mono_emit_jit_tramp (void *start, int size, const char *desc); gboolean mono_jit_map_is_enabled (void); #else #define mono_enable_jit_map() #define mono_emit_jit_map(ji) #define mono_emit_jit_tramp(s,z,d) do { } while (0) /* non-empty to avoid warning */ #define mono_jit_map_is_enabled() (0) #endif void mono_enable_jit_dump (void); void mono_emit_jit_dump (MonoJitInfo *jinfo, gpointer code); void mono_jit_dump_cleanup (void); gpointer mini_alloc_generic_virtual_trampoline (MonoVTable *vtable, int size); MonoException* mini_get_stack_overflow_ex (void); /* * Per-OS implementation functions. */ void mono_runtime_install_handlers (void); gboolean mono_runtime_install_custom_handlers (const char *handlers); void mono_runtime_install_custom_handlers_usage (void); void mono_runtime_setup_stat_profiler (void); void mono_runtime_posix_install_handlers (void); void mono_gdb_render_native_backtraces (pid_t crashed_pid); void mono_cross_helpers_run (void); void mono_init_native_crash_info (void); void mono_dump_native_crash_info (const char *signal, MonoContext *mctx, MONO_SIG_HANDLER_INFO_TYPE *info); void mono_post_native_crash_handler (const char *signal, MonoContext *mctx, MONO_SIG_HANDLER_INFO_TYPE *info, gboolean crash_chaining); gboolean mono_is_addr_implicit_null_check (void *addr); /* * Signal handling */ #if defined(DISABLE_HW_TRAPS) || defined(MONO_ARCH_DISABLE_HW_TRAPS) // Signal handlers not available #define MONO_ARCH_NEED_DIV_CHECK 1 #endif void MONO_SIG_HANDLER_SIGNATURE (mono_sigfpe_signal_handler) ; void MONO_SIG_HANDLER_SIGNATURE (mono_crashing_signal_handler) ; void MONO_SIG_HANDLER_SIGNATURE (mono_sigsegv_signal_handler); void MONO_SIG_HANDLER_SIGNATURE (mono_sigint_signal_handler) ; gboolean MONO_SIG_HANDLER_SIGNATURE (mono_chain_signal); #if defined (HOST_WASM) #define MONO_RETURN_ADDRESS_N(N) NULL #define MONO_RETURN_ADDRESS() MONO_RETURN_ADDRESS_N(0) #elif defined (__GNUC__) #define MONO_RETURN_ADDRESS_N(N) (__builtin_extract_return_addr (__builtin_return_address (N))) #define MONO_RETURN_ADDRESS() MONO_RETURN_ADDRESS_N(0) #elif defined(_MSC_VER) #include <intrin.h> #pragma intrinsic(_ReturnAddress) #define MONO_RETURN_ADDRESS() _ReturnAddress() #define MONO_RETURN_ADDRESS_N(N) NULL #else #error "Missing return address intrinsics implementation" #endif //have a global view of sdb disable #if !defined(MONO_ARCH_SOFT_DEBUG_SUPPORTED) || defined (DISABLE_DEBUGGER_AGENT) #define DISABLE_SDB 1 #endif void mini_register_sigterm_handler (void); #define MINI_BEGIN_CODEGEN() do { \ mono_codeman_enable_write (); \ } while (0) #define MINI_END_CODEGEN(buf,size,type,arg) do { \ mono_codeman_disable_write (); \ mono_arch_flush_icache ((buf), (size)); \ if ((int)type != -1) \ MONO_PROFILER_RAISE (jit_code_buffer, ((buf), (size), (MonoProfilerCodeBufferType)(type), (arg))); \ } while (0) #endif /* __MONO_MINI_RUNTIME_H__ */
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/vm/typestring.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // --------------------------------------------------------------------------- // typestring.cpp // --------------------------------------------------------------------------- // // // This module contains all helper functions required to produce // string representations of types, with options to control the // appearance of namespace and assembly information. Its primary use // is in reflection (Type.Name, Type.FullName, Type.ToString, etc) but // over time it could replace the use of TypeHandle.GetName etc for // diagnostic messages. // // --------------------------------------------------------------------------- #ifndef TYPESTRING_H #define TYPESTRING_H #include "common.h" #include "class.h" #include "typehandle.h" #include "sstring.h" #include "typekey.h" #include "typeparse.h" #include "field.h" class TypeString; class TypeNameBuilder { private: friend class TypeString; friend SString* TypeName::ToString(SString*, BOOL, BOOL, BOOL); friend TypeHandle TypeName::GetTypeWorker(BOOL, BOOL, Assembly*, BOOL, BOOL, Assembly*, AssemblyBinder * pBinder, OBJECTREF *); HRESULT OpenGenericArguments(); HRESULT CloseGenericArguments(); HRESULT OpenGenericArgument(); HRESULT CloseGenericArgument(); HRESULT AddName(LPCWSTR szName); HRESULT AddName(LPCWSTR szName, LPCWSTR szNamespace); HRESULT AddPointer(); HRESULT AddByRef(); HRESULT AddSzArray(); HRESULT AddArray(DWORD rank); HRESULT AddAssemblySpec(LPCWSTR szAssemblySpec); HRESULT ToString(BSTR* pszStringRepresentation); HRESULT Clear(); private: class Stack { public: Stack() : m_depth(0) { LIMITED_METHOD_CONTRACT; } public: COUNT_T Push(COUNT_T element) { WRAPPER_NO_CONTRACT; *m_stack.Append() = element; m_depth++; return Tos(); } COUNT_T Pop() { CONTRACTL { THROWS; GC_NOTRIGGER; MODE_ANY; PRECONDITION(GetDepth() > 0); } CONTRACTL_END; COUNT_T tos = Tos(); m_stack.Delete(m_stack.End() - 1); m_depth--; return tos; } COUNT_T Tos() { WRAPPER_NO_CONTRACT; return m_stack.End()[-1]; } void Clear() { WRAPPER_NO_CONTRACT; while(GetDepth()) Pop(); } COUNT_T GetDepth() { WRAPPER_NO_CONTRACT; return m_depth; } private: INT32 m_depth; InlineSArray<COUNT_T, 16> m_stack; }; public: typedef enum { ParseStateSTART = 0x0001, ParseStateNAME = 0x0004, ParseStateGENARGS = 0x0008, ParseStatePTRARR = 0x0010, ParseStateBYREF = 0x0020, ParseStateASSEMSPEC = 0x0080, ParseStateERROR = 0x0100, } ParseState; public: TypeNameBuilder(SString* pStr, ParseState parseState = ParseStateSTART); TypeNameBuilder() { WRAPPER_NO_CONTRACT; m_pStr = &m_str; Clear(); } void SetUseAngleBracketsForGenerics(BOOL value) { m_bUseAngleBracketsForGenerics = value; } void Append(LPCWSTR pStr) { WRAPPER_NO_CONTRACT; m_pStr->Append(pStr); } void Append(WCHAR c) { WRAPPER_NO_CONTRACT; m_pStr->Append(c); } SString* GetString() { WRAPPER_NO_CONTRACT; return m_pStr; } private: void EscapeName(LPCWSTR szName); void EscapeAssemblyName(LPCWSTR szName); void EscapeEmbeddedAssemblyName(LPCWSTR szName); BOOL CheckParseState(int validState) { WRAPPER_NO_CONTRACT; return ((int)m_parseState & validState) != 0; } //BOOL CheckParseState(int validState) { WRAPPER_NO_CONTRACT; ASSERT(((int)m_parseState & validState) != 0); return TRUE; } HRESULT Fail() { WRAPPER_NO_CONTRACT; m_parseState = ParseStateERROR; return E_FAIL; } void PushOpenGenericArgument(); void PopOpenGenericArgument(); private: ParseState m_parseState; SString* m_pStr; InlineSString<256> m_str; DWORD m_instNesting; BOOL m_bFirstInstArg; BOOL m_bNestedName; BOOL m_bHasAssemblySpec; BOOL m_bUseAngleBracketsForGenerics; Stack m_stack; }; // -------------------------------------------------------------------------- // This type can generate names for types. It is used by reflection methods // like System.RuntimeType.RuntimeTypeCache.ConstructName // class TypeString { // ----------------------------------------------------------------------- // WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING // ----------------------------------------------------------------------- // Do no change the formatting of these strings as they are used by // serialization, and it would break serialization backwards-compatibility. public: typedef enum { FormatBasic = 0x00000000, // Not a bitmask, simply the tersest flag settings possible FormatNamespace = 0x00000001, // Include namespace and/or enclosing class names in type names FormatFullInst = 0x00000002, // Include namespace and assembly in generic types (regardless of other flag settings) FormatAssembly = 0x00000004, // Include assembly display name in type names FormatSignature = 0x00000008, // Include signature in method names FormatNoVersion = 0x00000010, // Suppress version and culture information in all assembly names #ifdef _DEBUG FormatDebug = 0x00000020, // For debug printing of types only #endif FormatAngleBrackets = 0x00000040, // Whether generic types are C<T> or C[T] FormatStubInfo = 0x00000080, // Include stub info like {unbox-stub} FormatGenericParam = 0x00000100, // Use !name and !!name for generic type and method parameters } FormatFlags; public: // Append the name of the type td to the string // The following flags in the FormatFlags argument are significant: FormatNamespace static void AppendTypeDef(SString& tnb, IMDInternalImport *pImport, mdTypeDef td, DWORD format = FormatNamespace); // Append a square-bracket-enclosed, comma-separated list of n type parameters in inst to the string s // and enclose each parameter in square brackets to disambiguate the commas // The following flags in the FormatFlags argument are significant: FormatNamespace FormatFullInst FormatAssembly FormatNoVersion static void AppendInst(SString& s, Instantiation inst, DWORD format = FormatNamespace); // Append a representation of the type t to the string s // The following flags in the FormatFlags argument are significant: FormatNamespace FormatFullInst FormatAssembly FormatNoVersion static void AppendType(SString& s, TypeHandle t, DWORD format = FormatNamespace); // Append a representation of the type t to the string s, using the generic // instantiation info provided, instead of the instantiation in the TypeHandle. static void AppendType(SString& s, TypeHandle t, Instantiation typeInstantiation, DWORD format = FormatNamespace); static void AppendTypeKey(SString& s, TypeKey *pTypeKey, DWORD format = FormatNamespace); // Appends the method name and generic instantiation info. This might // look like "Namespace.ClassName[T].Foo[U, V]()" static void AppendMethod(SString& s, MethodDesc *pMD, Instantiation typeInstantiation, const DWORD format = FormatNamespace|FormatSignature); // Append a representation of the method m to the string s // The following flags in the FormatFlags argument are significant: FormatNamespace FormatFullInst FormatAssembly FormatSignature FormatNoVersion static void AppendMethodInternal(SString& s, MethodDesc *pMD, const DWORD format = FormatNamespace|FormatSignature|FormatStubInfo); // Append the field name and generic instantiation info. static void AppendField(SString& s, FieldDesc *pFD, Instantiation typeInstantiation, const DWORD format = FormatNamespace); #ifdef _DEBUG // These versions are NOTHROWS. They are meant for diagnostic purposes only // as they may leave "s" in a bad state if there are any problems/exceptions. static void AppendMethodDebug(SString& s, MethodDesc *pMD); static void AppendTypeDebug(SString& s, TypeHandle t); static void AppendTypeKeyDebug(SString& s, TypeKey* pTypeKey); #endif private: friend class TypeNameBuilder; static void AppendMethodImpl(SString& s, MethodDesc *pMD, Instantiation typeInstantiation, const DWORD format); static void AppendTypeDef(TypeNameBuilder& tnb, IMDInternalImport *pImport, mdTypeDef td, DWORD format = FormatNamespace); static void AppendNestedTypeDef(TypeNameBuilder& tnb, IMDInternalImport *pImport, mdTypeDef td, DWORD format = FormatNamespace); static void AppendInst(TypeNameBuilder& tnb, Instantiation inst, DWORD format = FormatNamespace); static void AppendType(TypeNameBuilder& tnb, TypeHandle t, Instantiation typeInstantiation, DWORD format = FormatNamespace); // ???? static void AppendTypeKey(TypeNameBuilder& tnb, TypeKey *pTypeKey, DWORD format = FormatNamespace); static void AppendParamTypeQualifier(TypeNameBuilder& tnb, CorElementType kind, DWORD rank); static void EscapeSimpleTypeName(SString* ssTypeName, SString* ssEscapedTypeName); static bool ContainsReservedChar(LPCWSTR pTypeName); }; #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // --------------------------------------------------------------------------- // typestring.cpp // --------------------------------------------------------------------------- // // // This module contains all helper functions required to produce // string representations of types, with options to control the // appearance of namespace and assembly information. Its primary use // is in reflection (Type.Name, Type.FullName, Type.ToString, etc) but // over time it could replace the use of TypeHandle.GetName etc for // diagnostic messages. // // --------------------------------------------------------------------------- #ifndef TYPESTRING_H #define TYPESTRING_H #include "common.h" #include "class.h" #include "typehandle.h" #include "sstring.h" #include "typekey.h" #include "typeparse.h" #include "field.h" class TypeString; class TypeNameBuilder { private: friend class TypeString; friend SString* TypeName::ToString(SString*, BOOL, BOOL, BOOL); friend TypeHandle TypeName::GetTypeWorker(BOOL, BOOL, Assembly*, BOOL, BOOL, Assembly*, AssemblyBinder * pBinder, OBJECTREF *); HRESULT OpenGenericArguments(); HRESULT CloseGenericArguments(); HRESULT OpenGenericArgument(); HRESULT CloseGenericArgument(); HRESULT AddName(LPCWSTR szName); HRESULT AddName(LPCWSTR szName, LPCWSTR szNamespace); HRESULT AddPointer(); HRESULT AddByRef(); HRESULT AddSzArray(); HRESULT AddArray(DWORD rank); HRESULT AddAssemblySpec(LPCWSTR szAssemblySpec); HRESULT ToString(BSTR* pszStringRepresentation); HRESULT Clear(); private: class Stack { public: Stack() : m_depth(0) { LIMITED_METHOD_CONTRACT; } public: COUNT_T Push(COUNT_T element) { WRAPPER_NO_CONTRACT; *m_stack.Append() = element; m_depth++; return Tos(); } COUNT_T Pop() { CONTRACTL { THROWS; GC_NOTRIGGER; MODE_ANY; PRECONDITION(GetDepth() > 0); } CONTRACTL_END; COUNT_T tos = Tos(); m_stack.Delete(m_stack.End() - 1); m_depth--; return tos; } COUNT_T Tos() { WRAPPER_NO_CONTRACT; return m_stack.End()[-1]; } void Clear() { WRAPPER_NO_CONTRACT; while(GetDepth()) Pop(); } COUNT_T GetDepth() { WRAPPER_NO_CONTRACT; return m_depth; } private: INT32 m_depth; InlineSArray<COUNT_T, 16> m_stack; }; public: typedef enum { ParseStateSTART = 0x0001, ParseStateNAME = 0x0004, ParseStateGENARGS = 0x0008, ParseStatePTRARR = 0x0010, ParseStateBYREF = 0x0020, ParseStateASSEMSPEC = 0x0080, ParseStateERROR = 0x0100, } ParseState; public: TypeNameBuilder(SString* pStr, ParseState parseState = ParseStateSTART); TypeNameBuilder() { WRAPPER_NO_CONTRACT; m_pStr = &m_str; Clear(); } void SetUseAngleBracketsForGenerics(BOOL value) { m_bUseAngleBracketsForGenerics = value; } void Append(LPCWSTR pStr) { WRAPPER_NO_CONTRACT; m_pStr->Append(pStr); } void Append(WCHAR c) { WRAPPER_NO_CONTRACT; m_pStr->Append(c); } SString* GetString() { WRAPPER_NO_CONTRACT; return m_pStr; } private: void EscapeName(LPCWSTR szName); void EscapeAssemblyName(LPCWSTR szName); void EscapeEmbeddedAssemblyName(LPCWSTR szName); BOOL CheckParseState(int validState) { WRAPPER_NO_CONTRACT; return ((int)m_parseState & validState) != 0; } //BOOL CheckParseState(int validState) { WRAPPER_NO_CONTRACT; ASSERT(((int)m_parseState & validState) != 0); return TRUE; } HRESULT Fail() { WRAPPER_NO_CONTRACT; m_parseState = ParseStateERROR; return E_FAIL; } void PushOpenGenericArgument(); void PopOpenGenericArgument(); private: ParseState m_parseState; SString* m_pStr; InlineSString<256> m_str; DWORD m_instNesting; BOOL m_bFirstInstArg; BOOL m_bNestedName; BOOL m_bHasAssemblySpec; BOOL m_bUseAngleBracketsForGenerics; Stack m_stack; }; // -------------------------------------------------------------------------- // This type can generate names for types. It is used by reflection methods // like System.RuntimeType.RuntimeTypeCache.ConstructName // class TypeString { // ----------------------------------------------------------------------- // WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING // ----------------------------------------------------------------------- // Do no change the formatting of these strings as they are used by // serialization, and it would break serialization backwards-compatibility. public: typedef enum { FormatBasic = 0x00000000, // Not a bitmask, simply the tersest flag settings possible FormatNamespace = 0x00000001, // Include namespace and/or enclosing class names in type names FormatFullInst = 0x00000002, // Include namespace and assembly in generic types (regardless of other flag settings) FormatAssembly = 0x00000004, // Include assembly display name in type names FormatSignature = 0x00000008, // Include signature in method names FormatNoVersion = 0x00000010, // Suppress version and culture information in all assembly names #ifdef _DEBUG FormatDebug = 0x00000020, // For debug printing of types only #endif FormatAngleBrackets = 0x00000040, // Whether generic types are C<T> or C[T] FormatStubInfo = 0x00000080, // Include stub info like {unbox-stub} FormatGenericParam = 0x00000100, // Use !name and !!name for generic type and method parameters } FormatFlags; public: // Append the name of the type td to the string // The following flags in the FormatFlags argument are significant: FormatNamespace static void AppendTypeDef(SString& tnb, IMDInternalImport *pImport, mdTypeDef td, DWORD format = FormatNamespace); // Append a square-bracket-enclosed, comma-separated list of n type parameters in inst to the string s // and enclose each parameter in square brackets to disambiguate the commas // The following flags in the FormatFlags argument are significant: FormatNamespace FormatFullInst FormatAssembly FormatNoVersion static void AppendInst(SString& s, Instantiation inst, DWORD format = FormatNamespace); // Append a representation of the type t to the string s // The following flags in the FormatFlags argument are significant: FormatNamespace FormatFullInst FormatAssembly FormatNoVersion static void AppendType(SString& s, TypeHandle t, DWORD format = FormatNamespace); // Append a representation of the type t to the string s, using the generic // instantiation info provided, instead of the instantiation in the TypeHandle. static void AppendType(SString& s, TypeHandle t, Instantiation typeInstantiation, DWORD format = FormatNamespace); static void AppendTypeKey(SString& s, TypeKey *pTypeKey, DWORD format = FormatNamespace); // Appends the method name and generic instantiation info. This might // look like "Namespace.ClassName[T].Foo[U, V]()" static void AppendMethod(SString& s, MethodDesc *pMD, Instantiation typeInstantiation, const DWORD format = FormatNamespace|FormatSignature); // Append a representation of the method m to the string s // The following flags in the FormatFlags argument are significant: FormatNamespace FormatFullInst FormatAssembly FormatSignature FormatNoVersion static void AppendMethodInternal(SString& s, MethodDesc *pMD, const DWORD format = FormatNamespace|FormatSignature|FormatStubInfo); // Append the field name and generic instantiation info. static void AppendField(SString& s, FieldDesc *pFD, Instantiation typeInstantiation, const DWORD format = FormatNamespace); #ifdef _DEBUG // These versions are NOTHROWS. They are meant for diagnostic purposes only // as they may leave "s" in a bad state if there are any problems/exceptions. static void AppendMethodDebug(SString& s, MethodDesc *pMD); static void AppendTypeDebug(SString& s, TypeHandle t); static void AppendTypeKeyDebug(SString& s, TypeKey* pTypeKey); #endif private: friend class TypeNameBuilder; static void AppendMethodImpl(SString& s, MethodDesc *pMD, Instantiation typeInstantiation, const DWORD format); static void AppendTypeDef(TypeNameBuilder& tnb, IMDInternalImport *pImport, mdTypeDef td, DWORD format = FormatNamespace); static void AppendNestedTypeDef(TypeNameBuilder& tnb, IMDInternalImport *pImport, mdTypeDef td, DWORD format = FormatNamespace); static void AppendInst(TypeNameBuilder& tnb, Instantiation inst, DWORD format = FormatNamespace); static void AppendType(TypeNameBuilder& tnb, TypeHandle t, Instantiation typeInstantiation, DWORD format = FormatNamespace); // ???? static void AppendTypeKey(TypeNameBuilder& tnb, TypeKey *pTypeKey, DWORD format = FormatNamespace); static void AppendParamTypeQualifier(TypeNameBuilder& tnb, CorElementType kind, DWORD rank); static void EscapeSimpleTypeName(SString* ssTypeName, SString* ssEscapedTypeName); static bool ContainsReservedChar(LPCWSTR pTypeName); }; #endif
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/mono/mono/eglib/gdir-win32.c
/* * Directory utility functions. * * Author: * Gonzalo Paniagua Javier ([email protected]) * * (C) 2006 Novell, Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "config.h" #include <glib.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <io.h> #include <winsock2.h> struct _GDir { HANDLE handle; gchar* current; gchar* next; }; GDir * g_dir_open (const gchar *path, guint flags, GError **gerror) { GDir *dir; gunichar2* path_utf16; gunichar2* path_utf16_search; WIN32_FIND_DATAW find_data; g_return_val_if_fail (path != NULL, NULL); g_return_val_if_fail (gerror == NULL || *gerror == NULL, NULL); dir = g_new0 (GDir, 1); path_utf16 = u8to16 (path); path_utf16_search = g_malloc ((wcslen(path_utf16) + 3)*sizeof(gunichar2)); wcscpy (path_utf16_search, path_utf16); wcscat (path_utf16_search, L"\\*"); dir->handle = FindFirstFileW (path_utf16_search, &find_data); if (dir->handle == INVALID_HANDLE_VALUE) { if (gerror) { gint err = errno; *gerror = g_error_new (G_LOG_DOMAIN, g_file_error_from_errno (err), strerror (err)); } g_free (path_utf16_search); g_free (path_utf16); g_free (dir); return NULL; } g_free (path_utf16_search); g_free (path_utf16); while ((wcscmp (find_data.cFileName, L".") == 0) || (wcscmp (find_data.cFileName, L"..") == 0)) { if (!FindNextFileW (dir->handle, &find_data)) { if (gerror) { gint err = errno; *gerror = g_error_new (G_LOG_DOMAIN, g_file_error_from_errno (err), strerror (err)); } g_free (dir); return NULL; } } dir->current = NULL; dir->next = u16to8 (find_data.cFileName); return dir; } const gchar * g_dir_read_name (GDir *dir) { WIN32_FIND_DATAW find_data; g_return_val_if_fail (dir != NULL && dir->handle != 0, NULL); if (dir->current) g_free (dir->current); dir->current = NULL; dir->current = dir->next; if (!dir->current) return NULL; dir->next = NULL; do { if (!FindNextFileW (dir->handle, &find_data)) { dir->next = NULL; return dir->current; } } while ((wcscmp (find_data.cFileName, L".") == 0) || (wcscmp (find_data.cFileName, L"..") == 0)); dir->next = u16to8 (find_data.cFileName); return dir->current; } void g_dir_rewind (GDir *dir) { } void g_dir_close (GDir *dir) { g_return_if_fail (dir != NULL && dir->handle != 0); if (dir->current) g_free (dir->current); dir->current = NULL; if (dir->next) g_free (dir->next); dir->next = NULL; FindClose (dir->handle); dir->handle = 0; g_free (dir); }
/* * Directory utility functions. * * Author: * Gonzalo Paniagua Javier ([email protected]) * * (C) 2006 Novell, Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "config.h" #include <glib.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <io.h> #include <winsock2.h> struct _GDir { HANDLE handle; gchar* current; gchar* next; }; GDir * g_dir_open (const gchar *path, guint flags, GError **gerror) { GDir *dir; gunichar2* path_utf16; gunichar2* path_utf16_search; WIN32_FIND_DATAW find_data; g_return_val_if_fail (path != NULL, NULL); g_return_val_if_fail (gerror == NULL || *gerror == NULL, NULL); dir = g_new0 (GDir, 1); path_utf16 = u8to16 (path); path_utf16_search = g_malloc ((wcslen(path_utf16) + 3)*sizeof(gunichar2)); wcscpy (path_utf16_search, path_utf16); wcscat (path_utf16_search, L"\\*"); dir->handle = FindFirstFileW (path_utf16_search, &find_data); if (dir->handle == INVALID_HANDLE_VALUE) { if (gerror) { gint err = errno; *gerror = g_error_new (G_LOG_DOMAIN, g_file_error_from_errno (err), strerror (err)); } g_free (path_utf16_search); g_free (path_utf16); g_free (dir); return NULL; } g_free (path_utf16_search); g_free (path_utf16); while ((wcscmp (find_data.cFileName, L".") == 0) || (wcscmp (find_data.cFileName, L"..") == 0)) { if (!FindNextFileW (dir->handle, &find_data)) { if (gerror) { gint err = errno; *gerror = g_error_new (G_LOG_DOMAIN, g_file_error_from_errno (err), strerror (err)); } g_free (dir); return NULL; } } dir->current = NULL; dir->next = u16to8 (find_data.cFileName); return dir; } const gchar * g_dir_read_name (GDir *dir) { WIN32_FIND_DATAW find_data; g_return_val_if_fail (dir != NULL && dir->handle != 0, NULL); if (dir->current) g_free (dir->current); dir->current = NULL; dir->current = dir->next; if (!dir->current) return NULL; dir->next = NULL; do { if (!FindNextFileW (dir->handle, &find_data)) { dir->next = NULL; return dir->current; } } while ((wcscmp (find_data.cFileName, L".") == 0) || (wcscmp (find_data.cFileName, L"..") == 0)); dir->next = u16to8 (find_data.cFileName); return dir->current; } void g_dir_rewind (GDir *dir) { } void g_dir_close (GDir *dir) { g_return_if_fail (dir != NULL && dir->handle != 0); if (dir->current) g_free (dir->current); dir->current = NULL; if (dir->next) g_free (dir->next); dir->next = NULL; FindClose (dir->handle); dir->handle = 0; g_free (dir); }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/pal/src/libunwind/src/sh/Gregs.c
/* libunwind - a platform-independent unwind library Copyright (C) 2008 CodeSourcery Copyright (C) 2012 Tommi Rantala <[email protected]> This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "unwind_i.h" HIDDEN int tdep_access_reg (struct cursor *c, unw_regnum_t reg, unw_word_t *valp, int write) { dwarf_loc_t loc = DWARF_NULL_LOC; switch (reg) { case UNW_SH_PC: if (write) c->dwarf.ip = *valp; /* update the IP cache */ case UNW_SH_R0: case UNW_SH_R1: case UNW_SH_R2: case UNW_SH_R3: case UNW_SH_R4: case UNW_SH_R5: case UNW_SH_R6: case UNW_SH_R7: case UNW_SH_R8: case UNW_SH_R9: case UNW_SH_R10: case UNW_SH_R11: case UNW_SH_R12: case UNW_SH_R13: case UNW_SH_R14: case UNW_SH_PR: loc = c->dwarf.loc[reg]; break; case UNW_SH_R15: if (write) return -UNW_EREADONLYREG; *valp = c->dwarf.cfa; return 0; default: Debug (1, "bad register number %u\n", reg); return -UNW_EBADREG; } if (write) return dwarf_put (&c->dwarf, loc, *valp); else return dwarf_get (&c->dwarf, loc, valp); } HIDDEN int tdep_access_fpreg (struct cursor *c, unw_regnum_t reg, unw_fpreg_t *valp, int write) { Debug (1, "bad register number %u\n", reg); return -UNW_EBADREG; }
/* libunwind - a platform-independent unwind library Copyright (C) 2008 CodeSourcery Copyright (C) 2012 Tommi Rantala <[email protected]> This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "unwind_i.h" HIDDEN int tdep_access_reg (struct cursor *c, unw_regnum_t reg, unw_word_t *valp, int write) { dwarf_loc_t loc = DWARF_NULL_LOC; switch (reg) { case UNW_SH_PC: if (write) c->dwarf.ip = *valp; /* update the IP cache */ case UNW_SH_R0: case UNW_SH_R1: case UNW_SH_R2: case UNW_SH_R3: case UNW_SH_R4: case UNW_SH_R5: case UNW_SH_R6: case UNW_SH_R7: case UNW_SH_R8: case UNW_SH_R9: case UNW_SH_R10: case UNW_SH_R11: case UNW_SH_R12: case UNW_SH_R13: case UNW_SH_R14: case UNW_SH_PR: loc = c->dwarf.loc[reg]; break; case UNW_SH_R15: if (write) return -UNW_EREADONLYREG; *valp = c->dwarf.cfa; return 0; default: Debug (1, "bad register number %u\n", reg); return -UNW_EBADREG; } if (write) return dwarf_put (&c->dwarf, loc, *valp); else return dwarf_get (&c->dwarf, loc, valp); } HIDDEN int tdep_access_fpreg (struct cursor *c, unw_regnum_t reg, unw_fpreg_t *valp, int write) { Debug (1, "bad register number %u\n", reg); return -UNW_EBADREG; }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/pal/src/libunwind/tests/x64-unwind-badjmp-signal-frame.c
/* libunwind - a platform-independent unwind library Copyright (C) 2019 Brock York <twunknown AT gmail.com> This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <string.h> #include <execinfo.h> #include <sys/types.h> #include <sys/ucontext.h> #include <unistd.h> #ifdef HAVE_SYS_PTRACE_H #include <sys/ptrace.h> #endif #define UNW_LOCAL_ONLY #include <libunwind.h> /* * unwind in the signal handler checking the backtrace is correct * after a bad jump. */ void handle_sigsegv(int signal, siginfo_t *info, void *ucontext) { /* * 0 = success * !0 = general failure * 77 = test skipped * 99 = complete failure */ int test_status = 0; unw_cursor_t cursor; unw_context_t uc; unw_word_t ip, sp, offset; char name[1000]; int found_signal_frame = 0; int i = 0; char *names[] = { "", "main", }; int names_count = sizeof(names) / sizeof(*names); unw_getcontext(&uc); unw_init_local(&cursor, &uc); while (unw_step(&cursor) > 0 && !test_status) { if (unw_is_signal_frame(&cursor)) { found_signal_frame = 1; } if (found_signal_frame) { unw_get_reg(&cursor, UNW_REG_IP, &ip); unw_get_reg(&cursor, UNW_REG_SP, &sp); memset(name, 0, sizeof(char) * 1000); unw_get_proc_name(&cursor, name, sizeof(char) * 1000, &offset); printf("ip = %lx, sp = %lx offset = %lx name = %s\n", (long) ip, (long) sp, (long) offset, name); if (i < names_count) { if (strcmp(names[i], name) != 0) { test_status = 1; printf("frame %s doesn't match expected frame %s\n", name, names[i]); } else { i += 1; } } } } if (i != names_count) //Make sure we found all the frames! { printf("Failed to find all frames i:%d != names_count:%d\n", i, names_count); test_status = 1; } /*return test_status to test harness*/ exit(test_status); } void (*invalid_function)() = (void*)1; int main(int argc, char *argv[]) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_sigaction = handle_sigsegv; sa.sa_flags = SA_SIGINFO; sigaction(SIGSEGV, &sa, NULL); invalid_function(); /* * 99 is the hard error exit status for automake tests: * https://www.gnu.org/software/automake/manual/html_node/Scripts_002dbased-Testsuites.html#Scripts_002dbased-Testsuites * If we dont end up in the signal handler something went horribly wrong. */ return 99; }
/* libunwind - a platform-independent unwind library Copyright (C) 2019 Brock York <twunknown AT gmail.com> This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <string.h> #include <execinfo.h> #include <sys/types.h> #include <sys/ucontext.h> #include <unistd.h> #ifdef HAVE_SYS_PTRACE_H #include <sys/ptrace.h> #endif #define UNW_LOCAL_ONLY #include <libunwind.h> /* * unwind in the signal handler checking the backtrace is correct * after a bad jump. */ void handle_sigsegv(int signal, siginfo_t *info, void *ucontext) { /* * 0 = success * !0 = general failure * 77 = test skipped * 99 = complete failure */ int test_status = 0; unw_cursor_t cursor; unw_context_t uc; unw_word_t ip, sp, offset; char name[1000]; int found_signal_frame = 0; int i = 0; char *names[] = { "", "main", }; int names_count = sizeof(names) / sizeof(*names); unw_getcontext(&uc); unw_init_local(&cursor, &uc); while (unw_step(&cursor) > 0 && !test_status) { if (unw_is_signal_frame(&cursor)) { found_signal_frame = 1; } if (found_signal_frame) { unw_get_reg(&cursor, UNW_REG_IP, &ip); unw_get_reg(&cursor, UNW_REG_SP, &sp); memset(name, 0, sizeof(char) * 1000); unw_get_proc_name(&cursor, name, sizeof(char) * 1000, &offset); printf("ip = %lx, sp = %lx offset = %lx name = %s\n", (long) ip, (long) sp, (long) offset, name); if (i < names_count) { if (strcmp(names[i], name) != 0) { test_status = 1; printf("frame %s doesn't match expected frame %s\n", name, names[i]); } else { i += 1; } } } } if (i != names_count) //Make sure we found all the frames! { printf("Failed to find all frames i:%d != names_count:%d\n", i, names_count); test_status = 1; } /*return test_status to test harness*/ exit(test_status); } void (*invalid_function)() = (void*)1; int main(int argc, char *argv[]) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_sigaction = handle_sigsegv; sa.sa_flags = SA_SIGINFO; sigaction(SIGSEGV, &sa, NULL); invalid_function(); /* * 99 is the hard error exit status for automake tests: * https://www.gnu.org/software/automake/manual/html_node/Scripts_002dbased-Testsuites.html#Scripts_002dbased-Testsuites * If we dont end up in the signal handler something went horribly wrong. */ return 99; }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/pal/src/libunwind/src/x86/Gcreate_addr_space.c
/* libunwind - a platform-independent unwind library Copyright (C) 2003 Hewlett-Packard Co Contributed by David Mosberger-Tang <[email protected]> This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdlib.h> #include "unwind_i.h" #if defined(_LITTLE_ENDIAN) && !defined(__LITTLE_ENDIAN) #define __LITTLE_ENDIAN _LITTLE_ENDIAN #endif unw_addr_space_t unw_create_addr_space (unw_accessors_t *a, int byte_order) { #ifdef UNW_LOCAL_ONLY return NULL; #else unw_addr_space_t as; /* * x86 supports only little-endian. */ if (byte_order != 0 && byte_order != __LITTLE_ENDIAN) return NULL; as = malloc (sizeof (*as)); if (!as) return NULL; memset (as, 0, sizeof (*as)); as->acc = *a; return as; #endif }
/* libunwind - a platform-independent unwind library Copyright (C) 2003 Hewlett-Packard Co Contributed by David Mosberger-Tang <[email protected]> This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdlib.h> #include "unwind_i.h" #if defined(_LITTLE_ENDIAN) && !defined(__LITTLE_ENDIAN) #define __LITTLE_ENDIAN _LITTLE_ENDIAN #endif unw_addr_space_t unw_create_addr_space (unw_accessors_t *a, int byte_order) { #ifdef UNW_LOCAL_ONLY return NULL; #else unw_addr_space_t as; /* * x86 supports only little-endian. */ if (byte_order != 0 && byte_order != __LITTLE_ENDIAN) return NULL; as = malloc (sizeof (*as)); if (!as) return NULL; memset (as, 0, sizeof (*as)); as->acc = *a; return as; #endif }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/vm/exceptmacros.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // // EXCEPTMACROS.H - // // This header file exposes mechanisms to: // // 1. Throw COM+ exceptions using the COMPlusThrow() function // 2. Guard a block of code using EX_TRY, and catch // COM+ exceptions using EX_CATCH // // from the *unmanaged* portions of the EE. Much of the EE runs // in a hybrid state where it runs like managed code but the code // is produced by a classic unmanaged-code C++ compiler. // // THROWING A COM+ EXCEPTION // ------------------------- // To throw a COM+ exception, call the function: // // COMPlusThrow(OBJECTREF pThrowable); // // This function does not return. There are also various functions // that wrap COMPlusThrow for convenience. // // COMPlusThrow() must only be called within the scope of a EX_TRY // block. See below for more information. // // // THROWING A RUNTIME EXCEPTION // ---------------------------- // COMPlusThrow() is overloaded to take a constant describing // the common EE-generated exceptions, e.g. // // COMPlusThrow(kOutOfMemoryException); // // See rexcep.h for list of constants (prepend "k" to get the actual // constant name.) // // You can also add a descriptive error string as follows: // // - Add a descriptive error string and resource id to // COM99\src\dlls\mscorrc\resource.h and mscorrc.rc. // Embed "%1", "%2" or "%3" to leave room for runtime string // inserts. // // - Pass the resource ID and inserts to COMPlusThrow, i.e. // // COMPlusThrow(kSecurityException, // IDS_CANTREFORMATCDRIVEBECAUSE, // W("Formatting C drive permissions not granted.")); // // // // TO CATCH COMPLUS EXCEPTIONS: // ---------------------------- // // Use the following syntax: // // #include "exceptmacros.h" // // // OBJECTREF pThrownObject; // // EX_TRY { // ...guarded code... // } EX_CATCH { // ...handler... // } EX_END_CATCH(SwallowAllExceptions) // // // EX_TRY blocks can be nested. // // From within the handler, you can call the GET_THROWABLE() macro to // obtain the object that was thrown. // // CRUCIAL POINTS // -------------- // In order to call COMPlusThrow(), you *must* be within the scope // of a EX_TRY block. Under _DEBUG, COMPlusThrow() will assert // if you call it out of scope. This implies that just about every // external entrypoint into the EE has to have a EX_TRY, in order // to convert uncaught COM+ exceptions into some error mechanism // more understandable to its non-COM+ caller. // // Any function that can throw a COM+ exception out to its caller // has the same requirement. ALL such functions should be tagged // with THROWS in CONTRACT. Aside from making the code // self-document its contract, the checked version of this will fire // an assert if the function is ever called without being in scope. // // // AVOIDING EX_TRY GOTCHAS // ---------------------------- // EX_TRY/EX_CATCH actually expands into a Win32 SEH // __try/__except structure. It does a lot of goo under the covers // to deal with pre-emptive GC settings. // // 1. Do not use C++ or SEH try/__try use EX_TRY instead. // // 2. Remember that any function marked THROWS // has the potential not to return. So be wary of allocating // non-gc'd objects around such calls because ensuring cleanup // of these things is not simple (you can wrap another EX_TRY // around the call to simulate a COM+ "try-finally" but EX_TRY // is relatively expensive compared to the real thing.) // // #ifndef __exceptmacros_h__ #define __exceptmacros_h__ struct _EXCEPTION_REGISTRATION_RECORD; class Thread; class Frame; class Exception; VOID DECLSPEC_NORETURN RealCOMPlusThrowOM(); #include <excepcpu.h> //========================================================================== // Macros to allow catching exceptions from within the EE. These are lightweight // handlers that do not install the managed frame handler. // // struct Param { ... } param; // EE_TRY_FOR_FINALLY(Param *, pParam, &param) { // ...<guarded code>... // } EE_FINALLY { // ...<handler>... // } EE_END_FINALLY // // EE_TRY(filter expr) { // ...<guarded code>... // } EE_CATCH { // ...<handler>... // } //========================================================================== // __GotException will only be FALSE if got all the way through the code // guarded by the try, otherwise it will be TRUE, so we know if we got into the // finally from an exception or not. In which case need to reset the GC state back // to what it was for the finally to run in that state. #define EE_TRY_FOR_FINALLY(ParamType, paramDef, paramRef) \ { \ struct __EEParam \ { \ BOOL fGCDisabled; \ BOOL GotException; \ ParamType param; \ } __EEparam; \ __EEparam.fGCDisabled = GetThread()->PreemptiveGCDisabled(); \ __EEparam.GotException = TRUE; \ __EEparam.param = paramRef; \ PAL_TRY(__EEParam *, __pEEParam, &__EEparam) \ { \ ParamType paramDef; paramDef = __pEEParam->param; #define GOT_EXCEPTION() __EEparam.GotException #define EE_FINALLY \ __pEEParam->GotException = FALSE; \ } PAL_FINALLY { \ if (__EEparam.GotException) { \ if (__EEparam.fGCDisabled != GetThread()->PreemptiveGCDisabled()) { \ if (__EEparam.fGCDisabled) \ GetThread()->DisablePreemptiveGC(); \ else \ GetThread()->EnablePreemptiveGC(); \ } \ } #define EE_END_FINALLY \ } \ PAL_ENDTRY \ } //========================================================================== // Helpful macros to declare exception handlers, their implementaiton, // and to call them. //========================================================================== #define _EXCEPTION_HANDLER_DECL(funcname) \ EXCEPTION_DISPOSITION __cdecl funcname(EXCEPTION_RECORD *pExceptionRecord, \ struct _EXCEPTION_REGISTRATION_RECORD *pEstablisherFrame, \ CONTEXT *pContext, \ DISPATCHER_CONTEXT *pDispatcherContext) #define EXCEPTION_HANDLER_DECL(funcname) \ extern "C" _EXCEPTION_HANDLER_DECL(funcname) #define EXCEPTION_HANDLER_IMPL(funcname) \ _EXCEPTION_HANDLER_DECL(funcname) #define EXCEPTION_HANDLER_FWD(funcname) \ funcname(pExceptionRecord, pEstablisherFrame, pContext, pDispatcherContext) //========================================================================== // Declares a COM+ frame handler that can be used to make sure that // exceptions that should be handled from within managed code // are handled within and don't leak out to give other handlers a // chance at them. //========================================================================== #define INSTALL_COMPLUS_EXCEPTION_HANDLER() \ DECLARE_CPFH_EH_RECORD(GET_THREAD()); \ INSTALL_COMPLUS_EXCEPTION_HANDLER_NO_DECLARE() #define INSTALL_COMPLUS_EXCEPTION_HANDLER_NO_DECLARE() \ { \ INSTALL_EXCEPTION_HANDLING_RECORD(&(___pExRecord->m_ExReg)); \ /* work around unreachable code warning */ \ if (true) { #define UNINSTALL_COMPLUS_EXCEPTION_HANDLER() \ } \ UNINSTALL_EXCEPTION_HANDLING_RECORD(&(___pExRecord->m_ExReg)); \ } #if !defined(FEATURE_EH_FUNCLETS) #define INSTALL_NESTED_EXCEPTION_HANDLER(frame) \ NestedHandlerExRecord *__pNestedHandlerExRecord = (NestedHandlerExRecord*) _alloca(sizeof(NestedHandlerExRecord)); \ __pNestedHandlerExRecord->m_handlerInfo.m_hThrowable = NULL; \ __pNestedHandlerExRecord->Init((PEXCEPTION_ROUTINE)COMPlusNestedExceptionHandler, frame); \ INSTALL_EXCEPTION_HANDLING_RECORD(&(__pNestedHandlerExRecord->m_ExReg)); #define UNINSTALL_NESTED_EXCEPTION_HANDLER() \ UNINSTALL_EXCEPTION_HANDLING_RECORD(&(__pNestedHandlerExRecord->m_ExReg)); #else // defined(FEATURE_EH_FUNCLETS) #define INSTALL_NESTED_EXCEPTION_HANDLER(frame) #define UNINSTALL_NESTED_EXCEPTION_HANDLER() #endif // !defined(FEATURE_EH_FUNCLETS) LONG WINAPI CLRVectoredExceptionHandler(PEXCEPTION_POINTERS pExceptionInfo); // Actual UEF worker prototype for use by GCUnhandledExceptionFilter. extern LONG InternalUnhandledExceptionFilter_Worker(PEXCEPTION_POINTERS pExceptionInfo); VOID DECLSPEC_NORETURN RaiseTheExceptionInternalOnly(OBJECTREF throwable, BOOL rethrow, BOOL fForStackOverflow = FALSE); #if defined(DACCESS_COMPILE) #define INSTALL_UNWIND_AND_CONTINUE_HANDLER #define UNINSTALL_UNWIND_AND_CONTINUE_HANDLER #define INSTALL_UNWIND_AND_CONTINUE_HANDLER_NO_PROBE #define UNINSTALL_UNWIND_AND_CONTINUE_HANDLER_NO_PROBE #else // DACCESS_COMPILE void UnwindAndContinueRethrowHelperInsideCatch(Frame* pEntryFrame, Exception* pException); VOID DECLSPEC_NORETURN UnwindAndContinueRethrowHelperAfterCatch(Frame* pEntryFrame, Exception* pException); #ifdef TARGET_UNIX VOID DECLSPEC_NORETURN DispatchManagedException(PAL_SEHException& ex, bool isHardwareException); #define INSTALL_MANAGED_EXCEPTION_DISPATCHER \ PAL_SEHException exCopy; \ bool hasCaughtException = false; \ try { #define UNINSTALL_MANAGED_EXCEPTION_DISPATCHER \ } \ catch (PAL_SEHException& ex) \ { \ exCopy = std::move(ex); \ hasCaughtException = true; \ } \ if (hasCaughtException) \ { \ DispatchManagedException(exCopy, false);\ } // Install trap that catches unhandled managed exception and dumps its stack #define INSTALL_UNHANDLED_MANAGED_EXCEPTION_TRAP \ try { // Uninstall trap that catches unhandled managed exception and dumps its stack #define UNINSTALL_UNHANDLED_MANAGED_EXCEPTION_TRAP \ } \ catch (PAL_SEHException& ex) \ { \ if (!GetThread()->HasThreadStateNC(Thread::TSNC_ProcessedUnhandledException)) \ { \ LONG disposition = InternalUnhandledExceptionFilter_Worker(&ex.ExceptionPointers); \ _ASSERTE(disposition == EXCEPTION_CONTINUE_SEARCH); \ } \ CrashDumpAndTerminateProcess(1); \ UNREACHABLE(); \ } #else // TARGET_UNIX #define INSTALL_MANAGED_EXCEPTION_DISPATCHER #define UNINSTALL_MANAGED_EXCEPTION_DISPATCHER #define INSTALL_UNHANDLED_MANAGED_EXCEPTION_TRAP #define UNINSTALL_UNHANDLED_MANAGED_EXCEPTION_TRAP #endif // TARGET_UNIX #define INSTALL_UNWIND_AND_CONTINUE_HANDLER_NO_PROBE \ { \ MAKE_CURRENT_THREAD_AVAILABLE(); \ Exception* __pUnCException = NULL; \ Frame* __pUnCEntryFrame = CURRENT_THREAD->GetFrame(); \ bool __fExceptionCatched = false; \ SCAN_EHMARKER(); \ if (true) PAL_CPP_TRY { \ SCAN_EHMARKER_TRY(); \ DEBUG_ASSURE_NO_RETURN_BEGIN(IUACH) #define INSTALL_UNWIND_AND_CONTINUE_HANDLER \ INSTALL_UNWIND_AND_CONTINUE_HANDLER_NO_PROBE \ /* The purpose of the INSTALL_UNWIND_AND_CONTINUE_HANDLER is to translate an exception to a managed */ \ /* exception before it hits managed code. */ // Optimized version for helper method frame. Avoids redundant GetThread() calls. #define INSTALL_UNWIND_AND_CONTINUE_HANDLER_FOR_HMF(pHelperFrame) \ { \ Exception* __pUnCException = NULL; \ Frame* __pUnCEntryFrame = (pHelperFrame); \ bool __fExceptionCatched = false; \ SCAN_EHMARKER(); \ if (true) PAL_CPP_TRY { \ SCAN_EHMARKER_TRY(); \ DEBUG_ASSURE_NO_RETURN_BEGIN(IUACH); #define UNINSTALL_UNWIND_AND_CONTINUE_HANDLER_NO_PROBE \ DEBUG_ASSURE_NO_RETURN_END(IUACH) \ SCAN_EHMARKER_END_TRY(); \ } \ PAL_CPP_CATCH_DERIVED (Exception, __pException) \ { \ SCAN_EHMARKER_CATCH(); \ CONSISTENCY_CHECK(NULL != __pException); \ __pUnCException = __pException; \ UnwindAndContinueRethrowHelperInsideCatch(__pUnCEntryFrame, __pUnCException); \ __fExceptionCatched = true; \ SCAN_EHMARKER_END_CATCH(); \ } \ PAL_CPP_ENDTRY \ if (__fExceptionCatched) \ { \ SCAN_EHMARKER_CATCH(); \ UnwindAndContinueRethrowHelperAfterCatch(__pUnCEntryFrame, __pUnCException); \ } \ } \ #define UNINSTALL_UNWIND_AND_CONTINUE_HANDLER \ UNINSTALL_UNWIND_AND_CONTINUE_HANDLER_NO_PROBE; #endif // DACCESS_COMPILE #define ENCLOSE_IN_EXCEPTION_HANDLER( func ) \ { \ struct exception_handler_wrapper \ { \ static void wrap() \ { \ INSTALL_UNWIND_AND_CONTINUE_HANDLER; \ func(); \ UNINSTALL_UNWIND_AND_CONTINUE_HANDLER; \ } \ }; \ \ exception_handler_wrapper::wrap(); \ } //========================================================================== // Declares that a function can throw a COM+ exception. //========================================================================== #if defined(ENABLE_CONTRACTS) && !defined(DACCESS_COMPILE) //========================================================================== // Declares that a function cannot throw a COM+ exception. // Adds a record to the contract chain. //========================================================================== #define CANNOTTHROWCOMPLUSEXCEPTION() ANNOTATION_NOTHROW; \ COMPlusCannotThrowExceptionHelper _dummyvariable(TRUE, __FUNCTION__, __FILE__, __LINE__); extern const char *g_ExceptionFile; extern DWORD g_ExceptionLine; #define THROWLOG() ( g_ExceptionFile = __FILE__, g_ExceptionLine = __LINE__, TRUE ) #define COMPlusThrow if(THROWLOG() && 0) { } else RealCOMPlusThrow #define COMPlusThrowNonLocalized if(THROWLOG() && 0) { } else RealCOMPlusThrowNonLocalized #define COMPlusThrowHR if(THROWLOG() && 0) { } else RealCOMPlusThrowHR #define COMPlusThrowWin32 if(THROWLOG() && 0) { } else RealCOMPlusThrowWin32 #define COMPlusThrowOM if(THROWLOG() && 0) { } else RealCOMPlusThrowOM #define COMPlusThrowArithmetic if(THROWLOG() && 0) { } else RealCOMPlusThrowArithmetic #define COMPlusThrowArgumentNull if(THROWLOG() && 0) { } else RealCOMPlusThrowArgumentNull #define COMPlusThrowArgumentOutOfRange if(THROWLOG() && 0) { } else RealCOMPlusThrowArgumentOutOfRange #define COMPlusThrowArgumentException if(THROWLOG() && 0) { } else RealCOMPlusThrowArgumentException #define COMPlusThrowInvalidCastException if(THROWLOG() && 0) { } else RealCOMPlusThrowInvalidCastException #define COMPlusRareRethrow if(THROWLOG() && 0) { } else RealCOMPlusRareRethrow #else // ENABLE_CONTRACTS && !DACCESS_COMPILE #define CANNOTTHROWCOMPLUSEXCEPTION() ANNOTATION_NOTHROW #define BEGINCANNOTTHROWCOMPLUSEXCEPTION_SEH() ANNOTATION_NOTHROW #define ENDCANNOTTHROWCOMPLUSEXCEPTION_SEH() #define COMPlusThrow RealCOMPlusThrow #define COMPlusThrowNonLocalized RealCOMPlusThrowNonLocalized #ifndef DACCESS_COMPILE #define COMPlusThrowHR RealCOMPlusThrowHR #else #define COMPlusThrowHR ThrowHR #endif #define COMPlusThrowWin32 RealCOMPlusThrowWin32 #define COMPlusThrowOM RealCOMPlusThrowOM #define COMPlusThrowArithmetic RealCOMPlusThrowArithmetic #define COMPlusThrowArgumentNull RealCOMPlusThrowArgumentNull #define COMPlusThrowArgumentOutOfRange RealCOMPlusThrowArgumentOutOfRange #define COMPlusThrowArgumentException RealCOMPlusThrowArgumentException #define COMPlusThrowInvalidCastException RealCOMPlusThrowInvalidCastException #endif // ENABLE_CONTRACTS && !DACCESS_COMPILE /* Non-VM exception helpers to be rerouted inside the VM directory: ThrowHR ThrowWin32 ThrowLastError -->ThrowWin32(GetLastError()) ThrowOutOfMemory COMPlusThrowOM defers to this ThrowStackOverflow COMPlusThrowSO defers to this */ /* Ideally we could make these defines. But the sources in the VM directory won't build with them as defines. @todo: go through VM directory and eliminate calls to the non-VM style functions. #define ThrowHR COMPlusThrowHR #define ThrowWin32 COMPlusThrowWin32 #define ThrowLastError() COMPlusThrowWin32(GetLastError()) */ //====================================================== // Used when we're entering the EE from unmanaged code // and we can assert that the gc state is cooperative. // // If an exception is thrown through this transition // handler, it will clean up the EE appropriately. See // the definition of COMPlusCooperativeTransitionHandler // for the details. //====================================================== void COMPlusCooperativeTransitionHandler(Frame* pFrame); #define COOPERATIVE_TRANSITION_BEGIN() \ { \ MAKE_CURRENT_THREAD_AVAILABLE(); \ BEGIN_GCX_ASSERT_PREEMP; \ CoopTransitionHolder __CoopTransition(CURRENT_THREAD); \ DEBUG_ASSURE_NO_RETURN_BEGIN(COOP_TRANSITION) #define COOPERATIVE_TRANSITION_END() \ DEBUG_ASSURE_NO_RETURN_END(COOP_TRANSITION) \ __CoopTransition.SuppressRelease(); \ END_GCX_ASSERT_PREEMP; \ } extern LONG UserBreakpointFilter(EXCEPTION_POINTERS *ep); extern LONG DefaultCatchFilter(EXCEPTION_POINTERS *ep, LPVOID pv); extern LONG DefaultCatchNoSwallowFilter(EXCEPTION_POINTERS *ep, LPVOID pv); // the only valid parameter for DefaultCatchFilter #define COMPLUS_EXCEPTION_EXECUTE_HANDLER (PVOID)EXCEPTION_EXECUTE_HANDLER struct DefaultCatchFilterParam { PVOID pv; // must be COMPLUS_EXCEPTION_EXECUTE_HANDLER DefaultCatchFilterParam() {} DefaultCatchFilterParam(PVOID _pv) : pv(_pv) {} }; template <typename T> LPCWSTR GetPathForErrorMessagesT(T *pImgObj) { SUPPORTS_DAC_HOST_ONLY; if (pImgObj) { return pImgObj->GetPathForErrorMessages(); } else { return W(""); } } VOID ThrowBadFormatWorker(UINT resID, LPCWSTR imageName DEBUGARG(_In_z_ const char *cond)); template <typename T> NOINLINE VOID ThrowBadFormatWorkerT(UINT resID, T * pImgObj DEBUGARG(_In_z_ const char *cond)) { #ifdef DACCESS_COMPILE ThrowBadFormatWorker(resID, nullptr DEBUGARG(cond)); #else LPCWSTR tmpStr = GetPathForErrorMessagesT(pImgObj); ThrowBadFormatWorker(resID, tmpStr DEBUGARG(cond)); #endif } // Worker macro for throwing BadImageFormat exceptions. // // resID: resource ID in mscorrc.rc. Message may not have substitutions. resID is permitted (but not encouraged) to be 0. // imgObj: one of Module* or PEAssembly* or PEImage* (must support GetPathForErrorMessages method.) // #define IfFailThrowBF(hresult, resID, imgObj) \ do \ { \ if (FAILED(hresult)) \ THROW_BAD_FORMAT(resID, imgObj); \ } \ while(0) #define THROW_BAD_FORMAT(resID, imgObj) do { THROW_BAD_FORMAT_MAYBE(FALSE, resID, imgObj); UNREACHABLE(); } while(0) // Conditional version of THROW_BAD_FORMAT. Do not use for new callsites. This is really meant to be a drop-in replacement // for the obsolete BAD_FORMAT_ASSERT. #define THROW_BAD_FORMAT_MAYBE(cond, resID, imgObj) \ do \ { \ if (!(cond)) \ { \ ThrowBadFormatWorkerT((resID), (imgObj) DEBUGARG(#cond)); \ } \ } \ while(0) // Same as above, but allows you to specify your own HRESULT #define THROW_HR_ERROR_WITH_INFO(hr, imgObj) RealCOMPlusThrowHR(hr, hr, GetPathForErrorMessagesT(imgObj)) #endif // __exceptmacros_h__
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // // EXCEPTMACROS.H - // // This header file exposes mechanisms to: // // 1. Throw COM+ exceptions using the COMPlusThrow() function // 2. Guard a block of code using EX_TRY, and catch // COM+ exceptions using EX_CATCH // // from the *unmanaged* portions of the EE. Much of the EE runs // in a hybrid state where it runs like managed code but the code // is produced by a classic unmanaged-code C++ compiler. // // THROWING A COM+ EXCEPTION // ------------------------- // To throw a COM+ exception, call the function: // // COMPlusThrow(OBJECTREF pThrowable); // // This function does not return. There are also various functions // that wrap COMPlusThrow for convenience. // // COMPlusThrow() must only be called within the scope of a EX_TRY // block. See below for more information. // // // THROWING A RUNTIME EXCEPTION // ---------------------------- // COMPlusThrow() is overloaded to take a constant describing // the common EE-generated exceptions, e.g. // // COMPlusThrow(kOutOfMemoryException); // // See rexcep.h for list of constants (prepend "k" to get the actual // constant name.) // // You can also add a descriptive error string as follows: // // - Add a descriptive error string and resource id to // COM99\src\dlls\mscorrc\resource.h and mscorrc.rc. // Embed "%1", "%2" or "%3" to leave room for runtime string // inserts. // // - Pass the resource ID and inserts to COMPlusThrow, i.e. // // COMPlusThrow(kSecurityException, // IDS_CANTREFORMATCDRIVEBECAUSE, // W("Formatting C drive permissions not granted.")); // // // // TO CATCH COMPLUS EXCEPTIONS: // ---------------------------- // // Use the following syntax: // // #include "exceptmacros.h" // // // OBJECTREF pThrownObject; // // EX_TRY { // ...guarded code... // } EX_CATCH { // ...handler... // } EX_END_CATCH(SwallowAllExceptions) // // // EX_TRY blocks can be nested. // // From within the handler, you can call the GET_THROWABLE() macro to // obtain the object that was thrown. // // CRUCIAL POINTS // -------------- // In order to call COMPlusThrow(), you *must* be within the scope // of a EX_TRY block. Under _DEBUG, COMPlusThrow() will assert // if you call it out of scope. This implies that just about every // external entrypoint into the EE has to have a EX_TRY, in order // to convert uncaught COM+ exceptions into some error mechanism // more understandable to its non-COM+ caller. // // Any function that can throw a COM+ exception out to its caller // has the same requirement. ALL such functions should be tagged // with THROWS in CONTRACT. Aside from making the code // self-document its contract, the checked version of this will fire // an assert if the function is ever called without being in scope. // // // AVOIDING EX_TRY GOTCHAS // ---------------------------- // EX_TRY/EX_CATCH actually expands into a Win32 SEH // __try/__except structure. It does a lot of goo under the covers // to deal with pre-emptive GC settings. // // 1. Do not use C++ or SEH try/__try use EX_TRY instead. // // 2. Remember that any function marked THROWS // has the potential not to return. So be wary of allocating // non-gc'd objects around such calls because ensuring cleanup // of these things is not simple (you can wrap another EX_TRY // around the call to simulate a COM+ "try-finally" but EX_TRY // is relatively expensive compared to the real thing.) // // #ifndef __exceptmacros_h__ #define __exceptmacros_h__ struct _EXCEPTION_REGISTRATION_RECORD; class Thread; class Frame; class Exception; VOID DECLSPEC_NORETURN RealCOMPlusThrowOM(); #include <excepcpu.h> //========================================================================== // Macros to allow catching exceptions from within the EE. These are lightweight // handlers that do not install the managed frame handler. // // struct Param { ... } param; // EE_TRY_FOR_FINALLY(Param *, pParam, &param) { // ...<guarded code>... // } EE_FINALLY { // ...<handler>... // } EE_END_FINALLY // // EE_TRY(filter expr) { // ...<guarded code>... // } EE_CATCH { // ...<handler>... // } //========================================================================== // __GotException will only be FALSE if got all the way through the code // guarded by the try, otherwise it will be TRUE, so we know if we got into the // finally from an exception or not. In which case need to reset the GC state back // to what it was for the finally to run in that state. #define EE_TRY_FOR_FINALLY(ParamType, paramDef, paramRef) \ { \ struct __EEParam \ { \ BOOL fGCDisabled; \ BOOL GotException; \ ParamType param; \ } __EEparam; \ __EEparam.fGCDisabled = GetThread()->PreemptiveGCDisabled(); \ __EEparam.GotException = TRUE; \ __EEparam.param = paramRef; \ PAL_TRY(__EEParam *, __pEEParam, &__EEparam) \ { \ ParamType paramDef; paramDef = __pEEParam->param; #define GOT_EXCEPTION() __EEparam.GotException #define EE_FINALLY \ __pEEParam->GotException = FALSE; \ } PAL_FINALLY { \ if (__EEparam.GotException) { \ if (__EEparam.fGCDisabled != GetThread()->PreemptiveGCDisabled()) { \ if (__EEparam.fGCDisabled) \ GetThread()->DisablePreemptiveGC(); \ else \ GetThread()->EnablePreemptiveGC(); \ } \ } #define EE_END_FINALLY \ } \ PAL_ENDTRY \ } //========================================================================== // Helpful macros to declare exception handlers, their implementaiton, // and to call them. //========================================================================== #define _EXCEPTION_HANDLER_DECL(funcname) \ EXCEPTION_DISPOSITION __cdecl funcname(EXCEPTION_RECORD *pExceptionRecord, \ struct _EXCEPTION_REGISTRATION_RECORD *pEstablisherFrame, \ CONTEXT *pContext, \ DISPATCHER_CONTEXT *pDispatcherContext) #define EXCEPTION_HANDLER_DECL(funcname) \ extern "C" _EXCEPTION_HANDLER_DECL(funcname) #define EXCEPTION_HANDLER_IMPL(funcname) \ _EXCEPTION_HANDLER_DECL(funcname) #define EXCEPTION_HANDLER_FWD(funcname) \ funcname(pExceptionRecord, pEstablisherFrame, pContext, pDispatcherContext) //========================================================================== // Declares a COM+ frame handler that can be used to make sure that // exceptions that should be handled from within managed code // are handled within and don't leak out to give other handlers a // chance at them. //========================================================================== #define INSTALL_COMPLUS_EXCEPTION_HANDLER() \ DECLARE_CPFH_EH_RECORD(GET_THREAD()); \ INSTALL_COMPLUS_EXCEPTION_HANDLER_NO_DECLARE() #define INSTALL_COMPLUS_EXCEPTION_HANDLER_NO_DECLARE() \ { \ INSTALL_EXCEPTION_HANDLING_RECORD(&(___pExRecord->m_ExReg)); \ /* work around unreachable code warning */ \ if (true) { #define UNINSTALL_COMPLUS_EXCEPTION_HANDLER() \ } \ UNINSTALL_EXCEPTION_HANDLING_RECORD(&(___pExRecord->m_ExReg)); \ } #if !defined(FEATURE_EH_FUNCLETS) #define INSTALL_NESTED_EXCEPTION_HANDLER(frame) \ NestedHandlerExRecord *__pNestedHandlerExRecord = (NestedHandlerExRecord*) _alloca(sizeof(NestedHandlerExRecord)); \ __pNestedHandlerExRecord->m_handlerInfo.m_hThrowable = NULL; \ __pNestedHandlerExRecord->Init((PEXCEPTION_ROUTINE)COMPlusNestedExceptionHandler, frame); \ INSTALL_EXCEPTION_HANDLING_RECORD(&(__pNestedHandlerExRecord->m_ExReg)); #define UNINSTALL_NESTED_EXCEPTION_HANDLER() \ UNINSTALL_EXCEPTION_HANDLING_RECORD(&(__pNestedHandlerExRecord->m_ExReg)); #else // defined(FEATURE_EH_FUNCLETS) #define INSTALL_NESTED_EXCEPTION_HANDLER(frame) #define UNINSTALL_NESTED_EXCEPTION_HANDLER() #endif // !defined(FEATURE_EH_FUNCLETS) LONG WINAPI CLRVectoredExceptionHandler(PEXCEPTION_POINTERS pExceptionInfo); // Actual UEF worker prototype for use by GCUnhandledExceptionFilter. extern LONG InternalUnhandledExceptionFilter_Worker(PEXCEPTION_POINTERS pExceptionInfo); VOID DECLSPEC_NORETURN RaiseTheExceptionInternalOnly(OBJECTREF throwable, BOOL rethrow, BOOL fForStackOverflow = FALSE); #if defined(DACCESS_COMPILE) #define INSTALL_UNWIND_AND_CONTINUE_HANDLER #define UNINSTALL_UNWIND_AND_CONTINUE_HANDLER #define INSTALL_UNWIND_AND_CONTINUE_HANDLER_NO_PROBE #define UNINSTALL_UNWIND_AND_CONTINUE_HANDLER_NO_PROBE #else // DACCESS_COMPILE void UnwindAndContinueRethrowHelperInsideCatch(Frame* pEntryFrame, Exception* pException); VOID DECLSPEC_NORETURN UnwindAndContinueRethrowHelperAfterCatch(Frame* pEntryFrame, Exception* pException); #ifdef TARGET_UNIX VOID DECLSPEC_NORETURN DispatchManagedException(PAL_SEHException& ex, bool isHardwareException); #define INSTALL_MANAGED_EXCEPTION_DISPATCHER \ PAL_SEHException exCopy; \ bool hasCaughtException = false; \ try { #define UNINSTALL_MANAGED_EXCEPTION_DISPATCHER \ } \ catch (PAL_SEHException& ex) \ { \ exCopy = std::move(ex); \ hasCaughtException = true; \ } \ if (hasCaughtException) \ { \ DispatchManagedException(exCopy, false);\ } // Install trap that catches unhandled managed exception and dumps its stack #define INSTALL_UNHANDLED_MANAGED_EXCEPTION_TRAP \ try { // Uninstall trap that catches unhandled managed exception and dumps its stack #define UNINSTALL_UNHANDLED_MANAGED_EXCEPTION_TRAP \ } \ catch (PAL_SEHException& ex) \ { \ if (!GetThread()->HasThreadStateNC(Thread::TSNC_ProcessedUnhandledException)) \ { \ LONG disposition = InternalUnhandledExceptionFilter_Worker(&ex.ExceptionPointers); \ _ASSERTE(disposition == EXCEPTION_CONTINUE_SEARCH); \ } \ CrashDumpAndTerminateProcess(1); \ UNREACHABLE(); \ } #else // TARGET_UNIX #define INSTALL_MANAGED_EXCEPTION_DISPATCHER #define UNINSTALL_MANAGED_EXCEPTION_DISPATCHER #define INSTALL_UNHANDLED_MANAGED_EXCEPTION_TRAP #define UNINSTALL_UNHANDLED_MANAGED_EXCEPTION_TRAP #endif // TARGET_UNIX #define INSTALL_UNWIND_AND_CONTINUE_HANDLER_NO_PROBE \ { \ MAKE_CURRENT_THREAD_AVAILABLE(); \ Exception* __pUnCException = NULL; \ Frame* __pUnCEntryFrame = CURRENT_THREAD->GetFrame(); \ bool __fExceptionCatched = false; \ SCAN_EHMARKER(); \ if (true) PAL_CPP_TRY { \ SCAN_EHMARKER_TRY(); \ DEBUG_ASSURE_NO_RETURN_BEGIN(IUACH) #define INSTALL_UNWIND_AND_CONTINUE_HANDLER \ INSTALL_UNWIND_AND_CONTINUE_HANDLER_NO_PROBE \ /* The purpose of the INSTALL_UNWIND_AND_CONTINUE_HANDLER is to translate an exception to a managed */ \ /* exception before it hits managed code. */ // Optimized version for helper method frame. Avoids redundant GetThread() calls. #define INSTALL_UNWIND_AND_CONTINUE_HANDLER_FOR_HMF(pHelperFrame) \ { \ Exception* __pUnCException = NULL; \ Frame* __pUnCEntryFrame = (pHelperFrame); \ bool __fExceptionCatched = false; \ SCAN_EHMARKER(); \ if (true) PAL_CPP_TRY { \ SCAN_EHMARKER_TRY(); \ DEBUG_ASSURE_NO_RETURN_BEGIN(IUACH); #define UNINSTALL_UNWIND_AND_CONTINUE_HANDLER_NO_PROBE \ DEBUG_ASSURE_NO_RETURN_END(IUACH) \ SCAN_EHMARKER_END_TRY(); \ } \ PAL_CPP_CATCH_DERIVED (Exception, __pException) \ { \ SCAN_EHMARKER_CATCH(); \ CONSISTENCY_CHECK(NULL != __pException); \ __pUnCException = __pException; \ UnwindAndContinueRethrowHelperInsideCatch(__pUnCEntryFrame, __pUnCException); \ __fExceptionCatched = true; \ SCAN_EHMARKER_END_CATCH(); \ } \ PAL_CPP_ENDTRY \ if (__fExceptionCatched) \ { \ SCAN_EHMARKER_CATCH(); \ UnwindAndContinueRethrowHelperAfterCatch(__pUnCEntryFrame, __pUnCException); \ } \ } \ #define UNINSTALL_UNWIND_AND_CONTINUE_HANDLER \ UNINSTALL_UNWIND_AND_CONTINUE_HANDLER_NO_PROBE; #endif // DACCESS_COMPILE #define ENCLOSE_IN_EXCEPTION_HANDLER( func ) \ { \ struct exception_handler_wrapper \ { \ static void wrap() \ { \ INSTALL_UNWIND_AND_CONTINUE_HANDLER; \ func(); \ UNINSTALL_UNWIND_AND_CONTINUE_HANDLER; \ } \ }; \ \ exception_handler_wrapper::wrap(); \ } //========================================================================== // Declares that a function can throw a COM+ exception. //========================================================================== #if defined(ENABLE_CONTRACTS) && !defined(DACCESS_COMPILE) //========================================================================== // Declares that a function cannot throw a COM+ exception. // Adds a record to the contract chain. //========================================================================== #define CANNOTTHROWCOMPLUSEXCEPTION() ANNOTATION_NOTHROW; \ COMPlusCannotThrowExceptionHelper _dummyvariable(TRUE, __FUNCTION__, __FILE__, __LINE__); extern const char *g_ExceptionFile; extern DWORD g_ExceptionLine; #define THROWLOG() ( g_ExceptionFile = __FILE__, g_ExceptionLine = __LINE__, TRUE ) #define COMPlusThrow if(THROWLOG() && 0) { } else RealCOMPlusThrow #define COMPlusThrowNonLocalized if(THROWLOG() && 0) { } else RealCOMPlusThrowNonLocalized #define COMPlusThrowHR if(THROWLOG() && 0) { } else RealCOMPlusThrowHR #define COMPlusThrowWin32 if(THROWLOG() && 0) { } else RealCOMPlusThrowWin32 #define COMPlusThrowOM if(THROWLOG() && 0) { } else RealCOMPlusThrowOM #define COMPlusThrowArithmetic if(THROWLOG() && 0) { } else RealCOMPlusThrowArithmetic #define COMPlusThrowArgumentNull if(THROWLOG() && 0) { } else RealCOMPlusThrowArgumentNull #define COMPlusThrowArgumentOutOfRange if(THROWLOG() && 0) { } else RealCOMPlusThrowArgumentOutOfRange #define COMPlusThrowArgumentException if(THROWLOG() && 0) { } else RealCOMPlusThrowArgumentException #define COMPlusThrowInvalidCastException if(THROWLOG() && 0) { } else RealCOMPlusThrowInvalidCastException #define COMPlusRareRethrow if(THROWLOG() && 0) { } else RealCOMPlusRareRethrow #else // ENABLE_CONTRACTS && !DACCESS_COMPILE #define CANNOTTHROWCOMPLUSEXCEPTION() ANNOTATION_NOTHROW #define BEGINCANNOTTHROWCOMPLUSEXCEPTION_SEH() ANNOTATION_NOTHROW #define ENDCANNOTTHROWCOMPLUSEXCEPTION_SEH() #define COMPlusThrow RealCOMPlusThrow #define COMPlusThrowNonLocalized RealCOMPlusThrowNonLocalized #ifndef DACCESS_COMPILE #define COMPlusThrowHR RealCOMPlusThrowHR #else #define COMPlusThrowHR ThrowHR #endif #define COMPlusThrowWin32 RealCOMPlusThrowWin32 #define COMPlusThrowOM RealCOMPlusThrowOM #define COMPlusThrowArithmetic RealCOMPlusThrowArithmetic #define COMPlusThrowArgumentNull RealCOMPlusThrowArgumentNull #define COMPlusThrowArgumentOutOfRange RealCOMPlusThrowArgumentOutOfRange #define COMPlusThrowArgumentException RealCOMPlusThrowArgumentException #define COMPlusThrowInvalidCastException RealCOMPlusThrowInvalidCastException #endif // ENABLE_CONTRACTS && !DACCESS_COMPILE /* Non-VM exception helpers to be rerouted inside the VM directory: ThrowHR ThrowWin32 ThrowLastError -->ThrowWin32(GetLastError()) ThrowOutOfMemory COMPlusThrowOM defers to this ThrowStackOverflow COMPlusThrowSO defers to this */ /* Ideally we could make these defines. But the sources in the VM directory won't build with them as defines. @todo: go through VM directory and eliminate calls to the non-VM style functions. #define ThrowHR COMPlusThrowHR #define ThrowWin32 COMPlusThrowWin32 #define ThrowLastError() COMPlusThrowWin32(GetLastError()) */ //====================================================== // Used when we're entering the EE from unmanaged code // and we can assert that the gc state is cooperative. // // If an exception is thrown through this transition // handler, it will clean up the EE appropriately. See // the definition of COMPlusCooperativeTransitionHandler // for the details. //====================================================== void COMPlusCooperativeTransitionHandler(Frame* pFrame); #define COOPERATIVE_TRANSITION_BEGIN() \ { \ MAKE_CURRENT_THREAD_AVAILABLE(); \ BEGIN_GCX_ASSERT_PREEMP; \ CoopTransitionHolder __CoopTransition(CURRENT_THREAD); \ DEBUG_ASSURE_NO_RETURN_BEGIN(COOP_TRANSITION) #define COOPERATIVE_TRANSITION_END() \ DEBUG_ASSURE_NO_RETURN_END(COOP_TRANSITION) \ __CoopTransition.SuppressRelease(); \ END_GCX_ASSERT_PREEMP; \ } extern LONG UserBreakpointFilter(EXCEPTION_POINTERS *ep); extern LONG DefaultCatchFilter(EXCEPTION_POINTERS *ep, LPVOID pv); extern LONG DefaultCatchNoSwallowFilter(EXCEPTION_POINTERS *ep, LPVOID pv); // the only valid parameter for DefaultCatchFilter #define COMPLUS_EXCEPTION_EXECUTE_HANDLER (PVOID)EXCEPTION_EXECUTE_HANDLER struct DefaultCatchFilterParam { PVOID pv; // must be COMPLUS_EXCEPTION_EXECUTE_HANDLER DefaultCatchFilterParam() {} DefaultCatchFilterParam(PVOID _pv) : pv(_pv) {} }; template <typename T> LPCWSTR GetPathForErrorMessagesT(T *pImgObj) { SUPPORTS_DAC_HOST_ONLY; if (pImgObj) { return pImgObj->GetPathForErrorMessages(); } else { return W(""); } } VOID ThrowBadFormatWorker(UINT resID, LPCWSTR imageName DEBUGARG(_In_z_ const char *cond)); template <typename T> NOINLINE VOID ThrowBadFormatWorkerT(UINT resID, T * pImgObj DEBUGARG(_In_z_ const char *cond)) { #ifdef DACCESS_COMPILE ThrowBadFormatWorker(resID, nullptr DEBUGARG(cond)); #else LPCWSTR tmpStr = GetPathForErrorMessagesT(pImgObj); ThrowBadFormatWorker(resID, tmpStr DEBUGARG(cond)); #endif } // Worker macro for throwing BadImageFormat exceptions. // // resID: resource ID in mscorrc.rc. Message may not have substitutions. resID is permitted (but not encouraged) to be 0. // imgObj: one of Module* or PEAssembly* or PEImage* (must support GetPathForErrorMessages method.) // #define IfFailThrowBF(hresult, resID, imgObj) \ do \ { \ if (FAILED(hresult)) \ THROW_BAD_FORMAT(resID, imgObj); \ } \ while(0) #define THROW_BAD_FORMAT(resID, imgObj) do { THROW_BAD_FORMAT_MAYBE(FALSE, resID, imgObj); UNREACHABLE(); } while(0) // Conditional version of THROW_BAD_FORMAT. Do not use for new callsites. This is really meant to be a drop-in replacement // for the obsolete BAD_FORMAT_ASSERT. #define THROW_BAD_FORMAT_MAYBE(cond, resID, imgObj) \ do \ { \ if (!(cond)) \ { \ ThrowBadFormatWorkerT((resID), (imgObj) DEBUGARG(#cond)); \ } \ } \ while(0) // Same as above, but allows you to specify your own HRESULT #define THROW_HR_ERROR_WITH_INFO(hr, imgObj) RealCOMPlusThrowHR(hr, hr, GetPathForErrorMessagesT(imgObj)) #endif // __exceptmacros_h__
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/pal/src/libunwind/src/ppc32/Greg_states_iterate.c
/* libunwind - a platform-independent unwind library Copyright (c) 2002-2003 Hewlett-Packard Development Company, L.P. Contributed by David Mosberger-Tang <[email protected]> Modified for x86_64 by Max Asbock <[email protected]> This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "unwind_i.h" int unw_reg_states_iterate (unw_cursor_t *cursor, unw_reg_states_callback cb, void *token) { struct cursor *c = (struct cursor *) cursor; return dwarf_reg_states_iterate (&c->dwarf, cb, token); }
/* libunwind - a platform-independent unwind library Copyright (c) 2002-2003 Hewlett-Packard Development Company, L.P. Contributed by David Mosberger-Tang <[email protected]> Modified for x86_64 by Max Asbock <[email protected]> This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "unwind_i.h" int unw_reg_states_iterate (unw_cursor_t *cursor, unw_reg_states_callback cb, void *token) { struct cursor *c = (struct cursor *) cursor; return dwarf_reg_states_iterate (&c->dwarf, cb, token); }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/pal/tests/palsuite/composite/threading/threadsuspension_switchthread/readme.txt
To compile: 1) create a dat file (say threadsuspension.dat) with contents: PAL,Composite,palsuite\composite\threading\threadsuspension,wfmo=mainWrapper.c threadsuspension.c,<SUPPORTEXE>,<TESTLANGCPP>,<COMPILEONLY> 2) perl rrunmod.pl -r threadsuspension.dat To execute: mainWrapper [PROCESS_COUNT] [THREAD_COUNT] [REPEAT_COUNT]
To compile: 1) create a dat file (say threadsuspension.dat) with contents: PAL,Composite,palsuite\composite\threading\threadsuspension,wfmo=mainWrapper.c threadsuspension.c,<SUPPORTEXE>,<TESTLANGCPP>,<COMPILEONLY> 2) perl rrunmod.pl -r threadsuspension.dat To execute: mainWrapper [PROCESS_COUNT] [THREAD_COUNT] [REPEAT_COUNT]
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/pal/src/libunwind/src/hppa/Lget_save_loc.c
#define UNW_LOCAL_ONLY #include <libunwind.h> #if defined(UNW_LOCAL_ONLY) && !defined(UNW_REMOTE_ONLY) #include "Gget_save_loc.c" #endif
#define UNW_LOCAL_ONLY #include <libunwind.h> #if defined(UNW_LOCAL_ONLY) && !defined(UNW_REMOTE_ONLY) #include "Gget_save_loc.c" #endif
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/pal/inc/rt/conio.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // // =========================================================================== // File: conio.h // // =========================================================================== // dummy conio.h for PAL #include "palrt.h"
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // // =========================================================================== // File: conio.h // // =========================================================================== // dummy conio.h for PAL #include "palrt.h"
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/mono/mono/utils/mono-threads-state-machine.c
/** * \file */ #include <config.h> #include <mono/utils/mono-compiler.h> #include <mono/utils/mono-threads.h> #include <mono/utils/mono-tls.h> #include <mono/utils/mono-memory-model.h> #include <mono/utils/atomic.h> #include <mono/utils/checked-build.h> #include <mono/utils/mono-threads-debug.h> #include <errno.h> /*thread state helpers*/ static int get_thread_state (int thread_state) { const MonoThreadStateMachine state = {thread_state}; return state.state; } #if defined (THREADS_STATE_MACHINE_DEBUG_ENABLED) || defined (ENABLE_CHECKED_BUILD_THREAD) static int get_thread_suspend_count (int thread_state) { const MonoThreadStateMachine state = {thread_state}; return state.suspend_count; } #endif #ifdef THREADS_STATE_MACHINE_DEBUG_ENABLED static gboolean get_thread_no_safepoints (int thread_state) { const MonoThreadStateMachine state = {thread_state}; return state.no_safepoints; } #endif static MonoThreadStateMachine build_thread_state (int thread_state, int suspend_count, gboolean no_safepoints) { g_assert (suspend_count >= 0 && suspend_count <= THREAD_SUSPEND_COUNT_MAX); g_assert (thread_state >= 0 && thread_state <= STATE_MAX); no_safepoints = !!no_safepoints; // ensure it's 0 or 1 /* need a predictable value for the unused bits so that * thread_state_cas does not fail. */ MonoThreadStateMachine state = { 0 }; state.state = thread_state; state.no_safepoints = no_safepoints; state.suspend_count = suspend_count; return state; } static int thread_state_cas (MonoThreadStateMachine *state, MonoThreadStateMachine new_value, int old_raw) { return mono_atomic_cas_i32 (&state->raw, new_value.raw, old_raw); } static const char* state_name (int state) { static const char *state_names [] = { "STARTING", "DETACHED", "RUNNING", "ASYNC_SUSPENDED", "SELF_SUSPENDED", "ASYNC_SUSPEND_REQUESTED", "STATE_BLOCKING", "STATE_BLOCKING_ASYNC_SUSPENDED", "STATE_BLOCKING_SELF_SUSPENDED", "STATE_BLOCKING_SUSPEND_REQUESTED", }; return state_names [get_thread_state (state)]; } static void unwrap_thread_state (MonoThreadInfo* info, int *raw, int *cur, int *count, int *blk) { g_static_assert (sizeof (MonoThreadStateMachine) == sizeof (int32_t)); const MonoThreadStateMachine state = {mono_atomic_load_i32 (&info->thread_state.raw)}; // Read once from info and then read from local to get consistent values. *raw = state.raw; *cur = state.state; *count = state.suspend_count; *blk = state.no_safepoints; } #define UNWRAP_THREAD_STATE(RAW,CUR,COUNT,BLK,INFO) \ unwrap_thread_state ((INFO), &(RAW), &(CUR), &(COUNT), &(BLK)) static void check_thread_state (MonoThreadInfo* info) { #ifdef ENABLE_CHECKED_BUILD int raw_state, cur_state, suspend_count; gboolean no_safepoints; UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, no_safepoints, info); switch (cur_state) { case STATE_STARTING: case STATE_DETACHED: g_assert (!no_safepoints); /* fallthru */ case STATE_RUNNING: g_assert (suspend_count == 0); break; case STATE_BLOCKING_SELF_SUSPENDED: case STATE_BLOCKING_SUSPEND_REQUESTED: case STATE_BLOCKING_ASYNC_SUSPENDED: case STATE_ASYNC_SUSPENDED: case STATE_SELF_SUSPENDED: g_assert (!no_safepoints); /* fallthru */ case STATE_ASYNC_SUSPEND_REQUESTED: g_assert (suspend_count > 0); break; case STATE_BLOCKING: g_assert (!no_safepoints); g_assert (suspend_count == 0); break; default: g_error ("Invalid state %d", cur_state); } #endif } static void trace_state_change_with_func (const char *transition, MonoThreadInfo *info, int cur_raw_state, int next_state, gboolean next_no_safepoints, int suspend_count_delta, const char *func) { check_thread_state (info); THREADS_STATE_MACHINE_DEBUG ("[%s][%p] %s %s -> %s %s (%d -> %d) %s\n", transition, mono_thread_info_get_tid (info), state_name (get_thread_state (cur_raw_state)), (get_thread_no_safepoints (cur_raw_state) ? "X" : "."), state_name (next_state), (next_no_safepoints ? "X" : "."), get_thread_suspend_count (cur_raw_state), get_thread_suspend_count (cur_raw_state) + suspend_count_delta, func); CHECKED_BUILD_THREAD_TRANSITION (transition, info, get_thread_state (cur_raw_state), get_thread_suspend_count (cur_raw_state), next_state, suspend_count_delta); } static void trace_state_change_sigsafe (const char *transition, MonoThreadInfo *info, int cur_raw_state, int next_state, gboolean next_no_safepoints, int suspend_count_delta, const char *func) { check_thread_state (info); THREADS_STATE_MACHINE_DEBUG ("[%s][%p] %s %s -> %s %s (%d -> %d) %s\n", transition, mono_thread_info_get_tid (info), state_name (get_thread_state (cur_raw_state)), (get_thread_no_safepoints (cur_raw_state) ? "X" : "."), state_name (next_state), (next_no_safepoints ? "X" : "."), get_thread_suspend_count (cur_raw_state), get_thread_suspend_count (cur_raw_state) + suspend_count_delta, func); CHECKED_BUILD_THREAD_TRANSITION_NOBT (transition, info, get_thread_state (cur_raw_state), get_thread_suspend_count (cur_raw_state), next_state, suspend_count_delta); } static void trace_state_change (const char *transition, MonoThreadInfo *info, int cur_raw_state, int next_state, gboolean next_no_safepoints, int suspend_count_delta) // FIXME migrate all uses { trace_state_change_with_func (transition, info, cur_raw_state, next_state, next_no_safepoints, suspend_count_delta, ""); } /* This is the transition that signals that a thread is functioning. Its main goal is to catch threads been witnessed before been fully registered. */ void mono_threads_transition_attach (MonoThreadInfo* info) { int raw_state, cur_state, suspend_count; gboolean no_safepoints; retry_state_change: UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, no_safepoints, info); switch (cur_state) { case STATE_STARTING: if (!(suspend_count == 0)) mono_fatal_with_history ("suspend_count = %d, but should be == 0", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (thread_state_cas (&info->thread_state, build_thread_state (STATE_RUNNING, 0, 0), raw_state) != raw_state) goto retry_state_change; trace_state_change ("ATTACH", info, raw_state, STATE_RUNNING, FALSE, 0); break; default: mono_fatal_with_history ("Cannot transition current thread from %s with ATTACH", state_name (cur_state)); } } /* This is the transition that signals that a thread is no longer registered with the runtime. Its main goal is to catch threads been witnessed after they detach. This returns TRUE is the transition succeeded. If it returns false it means that there's a pending suspend that should be acted upon. */ gboolean mono_threads_transition_detach (MonoThreadInfo *info) { int raw_state, cur_state, suspend_count; gboolean no_safepoints; retry_state_change: UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, no_safepoints, info); switch (cur_state) { case STATE_RUNNING: case STATE_BLOCKING: /* An OS thread on coop goes STARTING->BLOCKING->RUNNING->BLOCKING->DETACHED */ if (!(suspend_count == 0)) mono_fatal_with_history ("suspend_count = %d, but should be == 0", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (thread_state_cas (&info->thread_state, build_thread_state (STATE_DETACHED, 0, 0), raw_state) != raw_state) goto retry_state_change; trace_state_change ("DETACH", info, raw_state, STATE_DETACHED, FALSE, 0); return TRUE; case STATE_ASYNC_SUSPEND_REQUESTED: //Can't detach until whoever asked us to suspend to be happy with us case STATE_BLOCKING_SUSPEND_REQUESTED: return FALSE; /* STATE_ASYNC_SUSPENDED: Code should not be running while suspended. STATE_SELF_SUSPENDED: Code should not be running while suspended. STATE_BLOCKING_SELF_SUSPENDED: This is a bug in coop x suspend that resulted the thread in an undetachable state. STATE_BLOCKING_ASYNC_SUSPENDED: Same as BLOCKING_SELF_SUSPENDED */ default: mono_fatal_with_history ("Cannot transition current thread %p from %s with DETACH", info, state_name (cur_state)); } } /* This transition initiates the suspension of another thread. Returns one of the following values: - ReqSuspendInitSuspendRunning: Thread suspend requested, caller must initiate suspend. - ReqSuspendInitSuspendBlocking: Thread in blocking state, caller may initiate suspend. - ReqSuspendAlreadySuspended: Thread was already suspended and not executing, nothing to do. - ReqSuspendAlreadySuspendedBlocking: Thread was already in blocking and a suspend was requested and the thread is still executing (perhaps in a syscall), nothing to do. */ MonoRequestSuspendResult mono_threads_transition_request_suspension (MonoThreadInfo *info) { int raw_state, cur_state, suspend_count; gboolean no_safepoints; g_assert (info != mono_thread_info_current ()); retry_state_change: UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, no_safepoints, info); switch (cur_state) { case STATE_RUNNING: //Post an async suspend request if (!(suspend_count == 0)) mono_fatal_with_history ("suspend_count = %d, but should be == 0", suspend_count); if (thread_state_cas (&info->thread_state, build_thread_state (STATE_ASYNC_SUSPEND_REQUESTED, 1, no_safepoints), raw_state) != raw_state) goto retry_state_change; trace_state_change ("SUSPEND_INIT_REQUESTED", info, raw_state, STATE_ASYNC_SUSPEND_REQUESTED, no_safepoints, 1); return ReqSuspendInitSuspendRunning; //This is the first async suspend request against the target case STATE_BLOCKING_SELF_SUSPENDED: case STATE_BLOCKING_ASYNC_SUSPENDED: case STATE_ASYNC_SUSPENDED: case STATE_SELF_SUSPENDED: if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (!(suspend_count > 0 && suspend_count < THREAD_SUSPEND_COUNT_MAX)) mono_fatal_with_history ("suspend_count = %d, but should be > 0 and < THREAD_SUSPEND_COUNT_MAX", suspend_count); if (thread_state_cas (&info->thread_state, build_thread_state (cur_state, suspend_count + 1, no_safepoints), raw_state) != raw_state) goto retry_state_change; trace_state_change ("SUSPEND_INIT_REQUESTED", info, raw_state, cur_state, no_safepoints, 1); return ReqSuspendAlreadySuspended; //Thread is already suspended so we don't need to wait it to suspend case STATE_BLOCKING: if (!(suspend_count == 0)) mono_fatal_with_history ("suspend_count = %d, but should be == 0", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (thread_state_cas (&info->thread_state, build_thread_state (STATE_BLOCKING_SUSPEND_REQUESTED, 1, no_safepoints), raw_state) != raw_state) goto retry_state_change; trace_state_change ("SUSPEND_INIT_REQUESTED", info, raw_state, STATE_BLOCKING_SUSPEND_REQUESTED, no_safepoints, 1); return ReqSuspendInitSuspendBlocking; //A thread in the blocking state has its state saved so we can treat it as suspended. case STATE_BLOCKING_SUSPEND_REQUESTED: /* This should only be happening if we're doing a cooperative suspend of a blocking thread. * In which case we could be in BLOCKING_SUSPEND_REQUESTED until we execute a done or abort blocking. * In preemptive suspend of a blocking thread since there's a single suspend initiator active at a time, * we would expect a finish_async_suspension or a done/abort blocking before the next suspension request */ if (!(suspend_count > 0 && suspend_count < THREAD_SUSPEND_COUNT_MAX)) mono_fatal_with_history ("suspend_count = %d, but should be > 0 and < THREAD_SUSPEND_COUNT_MAX", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (thread_state_cas (&info->thread_state, build_thread_state (cur_state, suspend_count + 1, no_safepoints), raw_state) != raw_state) goto retry_state_change; trace_state_change ("SUSPEND_INIT_REQUESTED", info, raw_state, cur_state, no_safepoints, 1); return ReqSuspendAlreadySuspendedBlocking; /* [1] It's questionable on what to do if we hit the beginning of a self suspend. The expected behavior is that the target should poll its state very soon so the the suspend latency should be minimal. STATE_ASYNC_SUSPEND_REQUESTED: Since there can only be one async suspend in progress and it must finish, it should not be possible to witness this. */ default: mono_fatal_with_history ("Cannot transition thread %p from %s with SUSPEND_INIT_REQUESTED", mono_thread_info_get_tid (info), state_name (cur_state)); } return (MonoRequestSuspendResult) FALSE; } /* Peek at the thread state and return whether it's BLOCKING_SUSPEND_REQUESTED or not. Assumes that it is called in the second phase of a two-phase suspend, so the thread is either some flavor of suspended or else blocking suspend requested. All other states can't happen. */ gboolean mono_threads_transition_peek_blocking_suspend_requested (MonoThreadInfo *info) { int raw_state, cur_state, suspend_count; gboolean no_safepoints; g_assert (info != mono_thread_info_current ()); UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, no_safepoints, info); switch (cur_state) { case STATE_ASYNC_SUSPENDED: case STATE_SELF_SUSPENDED: return FALSE; /*ReqPeekBlockingSuspendRequestedRunningSuspended;*/ case STATE_BLOCKING_SELF_SUSPENDED: case STATE_BLOCKING_ASYNC_SUSPENDED: case STATE_BLOCKING_SUSPEND_REQUESTED: if (!(suspend_count > 0 && suspend_count < THREAD_SUSPEND_COUNT_MAX)) mono_fatal_with_history ("suspend_count = %d, but should be > 0 and < THREAD_SUSPEND_COUNT_MAX", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (cur_state == STATE_BLOCKING_SUSPEND_REQUESTED) return TRUE; /*ReqPeekBlockingSuspendRequestedBlockingSuspendRequested;*/ else return FALSE; /*ReqPeekBlockingSuspendRequestedBlockingSuspended;*/ /* STATE_RUNNING: Can't happen - should have been suspended in the first phase. STATE_ASYNC_SUSPEND_REQUESTED Can't happen - first phase should've waited until the thread self-suspended STATE_BLOCKING: Can't happen - should've had a suspension request in the first phase. */ default: mono_fatal_with_history ("Thread %p in unexpected state %s with PEEK_BLOCKING_SUSPEND_REQUESTED", mono_thread_info_get_tid (info), state_name (cur_state)); } } /* Check the current state of the thread and try to init a self suspend. This must be called with self state saved. Returns one of the following values: - Resumed: Async resume happened and current thread should keep running - Suspend: Caller should wait for a resume signal - SelfSuspendNotifyAndWait: Notify the suspend initiator and wait for a resume signals suspend should start. */ MonoSelfSupendResult mono_threads_transition_state_poll (MonoThreadInfo *info) { int raw_state, cur_state, suspend_count; gboolean no_safepoints; g_assert (mono_thread_info_is_current (info)); retry_state_change: UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, no_safepoints, info); switch (cur_state) { case STATE_RUNNING: if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE in RUNNING with STATE_POLL"); if (!(suspend_count == 0)) mono_fatal_with_history ("suspend_count = %d, but should be == 0", suspend_count); trace_state_change ("STATE_POLL", info, raw_state, cur_state, no_safepoints, 0); return SelfSuspendResumed; //We're fine, don't suspend case STATE_ASYNC_SUSPEND_REQUESTED: //Async suspend requested, service it with a self suspend if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE in ASYNS_SUSPEND_REQUESTED with STATE_POLL"); if (!(suspend_count > 0)) mono_fatal_with_history ("suspend_count = %d, but should be > 0", suspend_count); if (thread_state_cas (&info->thread_state, build_thread_state (STATE_SELF_SUSPENDED, suspend_count, no_safepoints), raw_state) != raw_state) goto retry_state_change; trace_state_change ("STATE_POLL", info, raw_state, STATE_SELF_SUSPENDED, no_safepoints, 0); return SelfSuspendNotifyAndWait; //Caller should notify suspend initiator and wait for resume /* STATE_ASYNC_SUSPENDED: Code should not be running while suspended. STATE_SELF_SUSPENDED: Code should not be running while suspended. STATE_BLOCKING: STATE_BLOCKING_SUSPEND_REQUESTED: STATE_BLOCKING_ASYNC_SUSPENDED: STATE_BLOCKING_SELF_SUSPENDED: Poll is a local state transition. No VM activities are allowed while in blocking mode. (In all the blocking states - the local thread has no checkpoints, hence no polling, it can only do abort blocking or done blocking on itself). */ default: mono_fatal_with_history ("Cannot transition thread %p from %s with STATE_POLL", mono_thread_info_get_tid (info), state_name (cur_state)); } } /* Try to resume a suspended thread. Returns one of the following values: - Sucess: The thread was resumed. - Error: The thread was not suspended in the first place. [2] - InitSelfResume: The thread is blocked on self suspend and should be resumed - InitAsyncResume: The thread is blocked on async suspend and should be resumed - ResumeInitBlockingResume: The thread was suspended on the exit path of blocking state and should be resumed FIXME: ResumeInitBlockingResume is just InitSelfResume by a different name. [2] This threading system uses an unsigned suspend count. Which means a resume cannot be used as a suspend permit and cancel each other. Suspend permits are really useful to implement managed synchronization structures that don't consume native resources. The downside is that they further complicate the design of this system as the RUNNING state now has a non zero suspend counter. It can be implemented in the future if we find resume/suspend races that cannot be (efficiently) fixed by other means. One major issue with suspend permits is runtime facilities (GC, debugger) that must have the target suspended when requested. This would make permits really harder to add. */ MonoResumeResult mono_threads_transition_request_resume (MonoThreadInfo* info) { int raw_state, cur_state, suspend_count; gboolean no_safepoints; g_assert (info != mono_thread_info_current ()); //One can't self resume [3] retry_state_change: UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, no_safepoints, info); switch (cur_state) { case STATE_RUNNING: //Thread already running. if (!(suspend_count == 0)) mono_fatal_with_history ("suspend_count = %d, but should be == 0", suspend_count); trace_state_change ("RESUME", info, raw_state, cur_state, no_safepoints, 0); return ResumeError; //Resume failed because thread was not blocked case STATE_BLOCKING: //Blocking, might have a suspend count, we decrease if it's > 0 if (!(suspend_count == 0)) mono_fatal_with_history ("suspend_count = %d, but should be == 0", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); trace_state_change ("RESUME", info, raw_state, cur_state, no_safepoints, 0); return ResumeError; case STATE_BLOCKING_SUSPEND_REQUESTED: if (!(suspend_count > 0)) mono_fatal_with_history ("suspend_count = %d, but should be > 0", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (suspend_count > 1) { if (thread_state_cas (&info->thread_state, build_thread_state (cur_state, suspend_count - 1, no_safepoints), raw_state) != raw_state) goto retry_state_change; trace_state_change ("RESUME", info, raw_state, cur_state, no_safepoints, -1); return ResumeOk; //Resume worked and there's nothing for the caller to do. } else { if (thread_state_cas (&info->thread_state, build_thread_state (STATE_BLOCKING, 0, 0), raw_state) != raw_state) goto retry_state_change; trace_state_change ("RESUME", info, raw_state, STATE_BLOCKING, no_safepoints, -1); return ResumeOk; // Resume worked, back in blocking, nothing for the caller to do. } case STATE_BLOCKING_ASYNC_SUSPENDED: if (!(suspend_count > 0)) mono_fatal_with_history ("suspend_count = %d, but should be > 0", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (suspend_count > 1) { if (thread_state_cas (&info->thread_state, build_thread_state (cur_state, suspend_count - 1, no_safepoints), raw_state) != raw_state) goto retry_state_change; trace_state_change ("RESUME", info, raw_state, cur_state, no_safepoints, -1); return ResumeOk; // Resume worked, there's nothing else for the caller to do. } else { if (thread_state_cas (&info->thread_state, build_thread_state (STATE_BLOCKING, 0, 0), raw_state) != raw_state) goto retry_state_change; trace_state_change ("RESUME", info, raw_state, STATE_BLOCKING, no_safepoints, -1); return ResumeInitAsyncResume; // Resume worked and caller must do async resume, thread resumes in BLOCKING } case STATE_BLOCKING_SELF_SUSPENDED: //Decrease the suspend_count and maybe resume case STATE_ASYNC_SUSPENDED: case STATE_SELF_SUSPENDED: if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (!(suspend_count > 0)) mono_fatal_with_history ("suspend_count = %d, but should be > 0", suspend_count); if (suspend_count > 1) { if (thread_state_cas (&info->thread_state, build_thread_state (cur_state, suspend_count - 1, no_safepoints), raw_state) != raw_state) goto retry_state_change; trace_state_change ("RESUME", info, raw_state, cur_state, no_safepoints, -1); return ResumeOk; //Resume worked and there's nothing for the caller to do. } else { if (thread_state_cas (&info->thread_state, build_thread_state (STATE_RUNNING, 0, no_safepoints), raw_state) != raw_state) goto retry_state_change; trace_state_change ("RESUME", info, raw_state, STATE_RUNNING, no_safepoints, -1); if (cur_state == STATE_ASYNC_SUSPENDED) return ResumeInitAsyncResume; //Resume worked and caller must do async resume else if (cur_state == STATE_SELF_SUSPENDED) return ResumeInitSelfResume; //Resume worked and caller must do self resume else return ResumeInitBlockingResume; //Resume worked and caller must do blocking resume } /* STATE_ASYNC_SUSPEND_REQUESTED: Only one async suspend/resume operation can be in flight, so a resume cannot witness an internal state of suspend [3] A self-resume makes no sense given it requires the thread to be running, which means its suspend count must be zero. A self resume would make sense as a suspend permit, but as explained in [2] we don't support it so this is a bug. [4] It's questionable on whether a resume (an async operation) should be able to cancel a self suspend. The scenario where this would happen is similar to the one described in [2] when this is used for as a synchronization primitive. If this turns to be a problem we should either implement [2] or make this an invalid transition. */ default: mono_fatal_with_history ("Cannot transition thread %p from %s with REQUEST_RESUME", mono_thread_info_get_tid (info), state_name (cur_state)); } } /* Try to resume a suspended thread and atomically request that it suspend again. Returns one of the following values: - InitAsyncPulse: The thread is suspended with preemptive suspend and should be resumed. */ MonoPulseResult mono_threads_transition_request_pulse (MonoThreadInfo* info) { int raw_state, cur_state, suspend_count; gboolean no_safepoints; g_assert (info != mono_thread_info_current ()); //One can't self pulse [3] retry_state_change: UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, no_safepoints, info); switch (cur_state) { case STATE_BLOCKING_ASYNC_SUSPENDED: if (!(suspend_count == 1)) mono_fatal_with_history ("suspend_count = %d, but should be == 1", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (thread_state_cas (&info->thread_state, build_thread_state (STATE_BLOCKING_SUSPEND_REQUESTED, suspend_count, no_safepoints), raw_state) != raw_state) goto retry_state_change; trace_state_change ("PULSE", info, raw_state, STATE_BLOCKING_SUSPEND_REQUESTED, no_safepoints, -1); return PulseInitAsyncPulse; // Pulse worked and caller must do async pulse, thread pulses in BLOCKING /* STATE_RUNNING: STATE_BLOCKING: Only one suspend initiator at a time. Current STW stopped the thread and now needs to resume it. So thread must be in one of the suspended states if we get here. STATE_BLOCKING_SUSPEND_REQUESTED: STATE_ASYNC_SUSPEND_REQUESTED: Only one pulse operation can be in flight, so a pulse cannot witness an internal state of suspend STATE_ASYNC_SUSPENDED: Hybrid suspend shouldn't put GC Unsafe threads into async suspended state. STATE_BLOCKING_SELF_SUSPENDED: STATE_SELF_SUSPENDED: Don't expect these to be pulsed - they're not problematic. */ default: mono_fatal_with_history ("Cannot transition thread %p from %s with REQUEST_PULSE", mono_thread_info_get_tid (info), state_name (cur_state)); } } /* Abort last step of preemptive suspend in case of failure to async suspend thread. This function makes sure state machine reflects current state of thread (running/suspended) in case of failure to complete async suspend of thread. NOTE, thread can still have reached a suspend state (in case of self-suspend). Returns TRUE if async suspend request was successfully aborted. Thread should be in STATE_RUNNING. Returns FALSE if async suspend request was successfully aborted but thread already reached self-suspended. */ gboolean mono_threads_transition_abort_async_suspend (MonoThreadInfo* info) { int raw_state, cur_state, suspend_count; gboolean no_safepoints; retry_state_change: UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, no_safepoints, info); switch (cur_state) { case STATE_SELF_SUSPENDED: //async suspend raced with self suspend and lost case STATE_BLOCKING_SELF_SUSPENDED: //async suspend raced with blocking and lost if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); trace_state_change_sigsafe ("ABORT_ASYNC_SUSPEND", info, raw_state, cur_state, no_safepoints, 0, ""); return FALSE; //thread successfully reached suspend state. case STATE_ASYNC_SUSPEND_REQUESTED: case STATE_BLOCKING_SUSPEND_REQUESTED: if (!(suspend_count > 0)) mono_fatal_with_history ("suspend_count = %d, but should be > 0", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (suspend_count > 1) { if (thread_state_cas (&info->thread_state, build_thread_state (cur_state, suspend_count - 1, no_safepoints), raw_state) != raw_state) goto retry_state_change; trace_state_change ("ABORT_ASYNC_SUSPEND", info, raw_state, cur_state, no_safepoints, -1); } else { if (thread_state_cas (&info->thread_state, build_thread_state (STATE_RUNNING, 0, no_safepoints), raw_state) != raw_state) goto retry_state_change; trace_state_change ("ABORT_ASYNC_SUSPEND", info, raw_state, STATE_RUNNING, no_safepoints, -1); } return TRUE; //aborting thread suspend request succeded, thread is running. /* STATE_RUNNING: A thread cannot escape suspension once requested. STATE_ASYNC_SUSPENDED: There can be only one suspend initiator at a given time, meaning this state should have been visible on the first stage of suspend. STATE_BLOCKING: If a thread is subject to preemptive suspend, there is no race as the resume initiator should have suspended the thread to STATE_BLOCKING_ASYNC_SUSPENDED or STATE_BLOCKING_SELF_SUSPENDED before resuming. With cooperative suspend, there are no finish_async_suspend transitions since there's no path back from asyns_suspend requested to running. STATE_BLOCKING_ASYNC_SUSPENDED: There can only be one suspend initiator at a given time, meaning this state should have ben visible on the first stage of suspend. */ default: mono_fatal_with_history ("Cannot transition thread %p from %s with ABORT_ASYNC_SUSPEND", mono_thread_info_get_tid (info), state_name (cur_state)); } } /* This performs the last step of preemptive suspend. Returns TRUE if the caller should wait for resume. */ gboolean mono_threads_transition_finish_async_suspend (MonoThreadInfo* info) { int raw_state, cur_state, suspend_count; gboolean no_safepoints; retry_state_change: UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, no_safepoints, info); switch (cur_state) { case STATE_SELF_SUSPENDED: //async suspend raced with self suspend and lost case STATE_BLOCKING_SELF_SUSPENDED: //async suspend raced with blocking and lost if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); trace_state_change_sigsafe ("FINISH_ASYNC_SUSPEND", info, raw_state, cur_state, no_safepoints, 0, ""); return FALSE; //let self suspend wait case STATE_ASYNC_SUSPEND_REQUESTED: if (!(suspend_count > 0)) mono_fatal_with_history ("suspend_count = %d, but should be > 0", suspend_count); /* Don't expect to see no_safepoints, ever, with async */ if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE in ASYNC_SUSPEND_REQUESTED with FINISH_ASYNC_SUSPEND"); if (thread_state_cas (&info->thread_state, build_thread_state (STATE_ASYNC_SUSPENDED, suspend_count, FALSE), raw_state) != raw_state) goto retry_state_change; trace_state_change_sigsafe ("FINISH_ASYNC_SUSPEND", info, raw_state, STATE_ASYNC_SUSPENDED, FALSE, 0, ""); return TRUE; //Async suspend worked, now wait for resume case STATE_BLOCKING_SUSPEND_REQUESTED: if (!(suspend_count > 0)) mono_fatal_with_history ("suspend_count = %d, but should be > 0", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (thread_state_cas (&info->thread_state, build_thread_state (STATE_BLOCKING_ASYNC_SUSPENDED, suspend_count, FALSE), raw_state) != raw_state) goto retry_state_change; trace_state_change_sigsafe ("FINISH_ASYNC_SUSPEND", info, raw_state, STATE_BLOCKING_ASYNC_SUSPENDED, FALSE, 0, ""); return TRUE; //Async suspend of blocking thread worked, now wait for resume /* STATE_RUNNING: A thread cannot escape suspension once requested. STATE_ASYNC_SUSPENDED: There can be only one suspend initiator at a given time, meaning this state should have been visible on the first stage of suspend. STATE_BLOCKING: If a thread is subject to preemptive suspend, there is no race as the resume initiator should have suspended the thread to STATE_BLOCKING_ASYNC_SUSPENDED or STATE_BLOCKING_SELF_SUSPENDED before resuming. With cooperative suspend, there are no finish_async_suspend transitions since there's no path back from asyns_suspend requested to running. STATE_BLOCKING_ASYNC_SUSPENDED: There can only be one suspend initiator at a given time, meaning this state should have ben visible on the first stage of suspend. */ default: mono_fatal_with_history ("Cannot transition thread %p from %s with FINISH_ASYNC_SUSPEND", mono_thread_info_get_tid (info), state_name (cur_state)); } } /* This transitions the thread into a cooperative state where it's assumed to be suspended but can continue. Native runtime code might want to put itself into a state where the thread is considered suspended but can keep running. That state only works as long as the only managed state touched is blitable and was pinned before the transition. It returns the action the caller must perform: - Continue: Entered blocking state sucessfully; - PollAndRetry: Async suspend raced and won, try to suspend and then retry; */ MonoDoBlockingResult mono_threads_transition_do_blocking (MonoThreadInfo* info, const char *func) { int raw_state, cur_state, suspend_count; gboolean no_safepoints; retry_state_change: UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, no_safepoints, info); switch (cur_state) { case STATE_RUNNING: //transition to blocked if (!(suspend_count == 0)) mono_fatal_with_history ("suspend_count = %d, but should be == 0", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE in state RUNNING with DO_BLOCKING"); if (thread_state_cas (&info->thread_state, build_thread_state (STATE_BLOCKING, suspend_count, no_safepoints), raw_state) != raw_state) goto retry_state_change; trace_state_change ("DO_BLOCKING", info, raw_state, STATE_BLOCKING, no_safepoints, 0); return DoBlockingContinue; case STATE_ASYNC_SUSPEND_REQUESTED: if (!(suspend_count > 0)) mono_fatal_with_history ("suspend_count = %d, but should be > 0", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE in state ASYNC_SUSPEND_REQUESTED with DO_BLOCKING"); trace_state_change ("DO_BLOCKING", info, raw_state, cur_state, no_safepoints, 0); return DoBlockingPollAndRetry; /* STATE_ASYNC_SUSPENDED STATE_SELF_SUSPENDED: Code should not be running while suspended. STATE_BLOCKING: STATE_BLOCKING_SUSPEND_REQUESTED: STATE_BLOCKING_SELF_SUSPENDED: Blocking is not nestabled STATE_BLOCKING_ASYNC_SUSPENDED: Blocking is not nestable _and_ code should not be running while suspended */ default: mono_fatal_with_history ("%s Cannot transition thread %p from %s with DO_BLOCKING", func, mono_thread_info_get_tid (info), state_name (cur_state)); } } /* This is the exit transition from the blocking state. If this thread is logically async suspended it will have to wait until its resumed before continuing. It returns one of: -Ok: Done with blocking, just move on; -Wait: This thread was suspended while in blocking, wait for resume. */ MonoDoneBlockingResult mono_threads_transition_done_blocking (MonoThreadInfo* info, const char *func) { int raw_state, cur_state, suspend_count; gboolean no_safepoints; retry_state_change: UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, no_safepoints, info); switch (cur_state) { case STATE_BLOCKING: if (!(suspend_count == 0)) mono_fatal_with_history ("%s suspend_count = %d, but should be == 0", func, suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (thread_state_cas (&info->thread_state, build_thread_state (STATE_RUNNING, suspend_count, no_safepoints), raw_state) != raw_state) goto retry_state_change; trace_state_change_sigsafe ("DONE_BLOCKING", info, raw_state, STATE_RUNNING, no_safepoints, 0, func); return DoneBlockingOk; case STATE_BLOCKING_SUSPEND_REQUESTED: if (!(suspend_count > 0)) mono_fatal_with_history ("suspend_count = %d, but should be > 0", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (thread_state_cas (&info->thread_state, build_thread_state (STATE_BLOCKING_SELF_SUSPENDED, suspend_count, no_safepoints), raw_state) != raw_state) goto retry_state_change; trace_state_change_with_func ("DONE_BLOCKING", info, raw_state, STATE_BLOCKING_SELF_SUSPENDED, no_safepoints, 0, func); return DoneBlockingWait; /* STATE_RUNNING: //Blocking was aborted and not properly restored STATE_ASYNC_SUSPEND_REQUESTED: //Blocking was aborted, not properly restored and now there's a pending suspend STATE_ASYNC_SUSPENDED STATE_SELF_SUSPENDED: Code should not be running while suspended. STATE_BLOCKING_SELF_SUSPENDED: This an exit state of done blocking STATE_BLOCKING_ASYNC_SUSPENDED: This is an exit state of done blocking */ default: mono_fatal_with_history ("Cannot transition thread %p from %s with DONE_BLOCKING", mono_thread_info_get_tid (info), state_name (cur_state)); } } /* Transition a thread in what should be a blocking state back to running state. This is different that done blocking because the goal is to get back to blocking once we're done. This is required to be able to bail out of blocking in case we're back to inside the runtime. It returns one of: -Ignore: Thread was not in blocking, nothing to do; -IgnoreAndPoll: Thread was not blocking and there's a pending suspend that needs to be processed; -Ok: Blocking state successfully aborted; -Wait: Blocking state successfully aborted, there's a pending suspend to be processed though, wait for resume. */ MonoAbortBlockingResult mono_threads_transition_abort_blocking (THREAD_INFO_TYPE* info, const char *func) { int raw_state, cur_state, suspend_count; gboolean no_safepoints; retry_state_change: UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, no_safepoints, info); switch (cur_state) { case STATE_RUNNING: //thread already in runnable state /* Even though we're going to ignore this transition, still * assert about no_safepoints. Rationale: make it easier to catch * cases where we would be in ASYNC_SUSPEND_REQUESTED with * no_safepoints set, since those are polling points. */ if (no_safepoints) { /* reset the state to no safepoints and then abort. If a * thread asserts somewhere because no_safepoints was set when it * shouldn't have been, we would get a second assertion here while * unwinding if we hadn't reset the no_safepoints flag. */ if (thread_state_cas (&info->thread_state, build_thread_state (STATE_RUNNING, suspend_count, FALSE), raw_state) != raw_state) goto retry_state_change; /* record the current transition, in order to grab a backtrace */ trace_state_change_with_func ("ABORT_BLOCKING", info, raw_state, STATE_RUNNING, FALSE, 0, func); mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE in state RUNNING with ABORT_BLOCKING"); } trace_state_change_sigsafe ("ABORT_BLOCKING", info, raw_state, cur_state, no_safepoints, 0, func); return AbortBlockingIgnore; case STATE_ASYNC_SUSPEND_REQUESTED: //thread is runnable and have a pending suspend if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE in state ASYNC_SUSPEND_REQUESTED with ABORT_BLOCKING"); trace_state_change_sigsafe ("ABORT_BLOCKING", info, raw_state, cur_state, no_safepoints, 0, func); return AbortBlockingIgnoreAndPoll; case STATE_BLOCKING: if (!(suspend_count == 0)) mono_fatal_with_history ("suspend_count = %d, but should be == 0", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (thread_state_cas (&info->thread_state, build_thread_state (STATE_RUNNING, suspend_count, FALSE), raw_state) != raw_state) goto retry_state_change; trace_state_change_sigsafe ("ABORT_BLOCKING", info, raw_state, STATE_RUNNING, FALSE, 0, func); return AbortBlockingOk; case STATE_BLOCKING_SUSPEND_REQUESTED: if (!(suspend_count > 0)) mono_fatal_with_history ("suspend_count = %d, but should be > 0", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (thread_state_cas (&info->thread_state, build_thread_state (STATE_BLOCKING_SELF_SUSPENDED, suspend_count, FALSE), raw_state) != raw_state) goto retry_state_change; trace_state_change_with_func ("ABORT_BLOCKING", info, raw_state, STATE_BLOCKING_SELF_SUSPENDED, FALSE, 0, func); return AbortBlockingWait; /* STATE_ASYNC_SUSPENDED: STATE_SELF_SUSPENDED: Code should not be running while suspended. STATE_BLOCKING_SELF_SUSPENDED: This is an exit state of done blocking, can't happen here. STATE_BLOCKING_ASYNC_SUSPENDED: This is an exit state of abort blocking, can't happen here. */ default: mono_fatal_with_history ("Cannot transition thread %p from %s with ABORT_BLOCKING", mono_thread_info_get_tid (info), state_name (cur_state)); } } /* Set the no_safepoints flag on an executing GC Unsafe thread. The no_safepoints bit prevents polling (hence self-suspending) and transitioning from GC Unsafe to GC Safe. Thus the thread will not be (cooperatively) interrupted while the bit is set. We don't allow nesting no_safepoints regions, so the flag must be initially unset. Since a suspend initiator may at any time request that a thread should suspend, ASYNC_SUSPEND_REQUESTED is allowed to have the no_safepoints bit set, too. (Future: We could augment this function to return a return value that tells the thread to poll and retry the transition since if we enter here in the ASYNC_SUSPEND_REQUESTED state). */ void mono_threads_transition_begin_no_safepoints (MonoThreadInfo *info, const char *func) { int raw_state, cur_state, suspend_count; gboolean no_safepoints; retry_state_change: UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, no_safepoints, info); switch (cur_state) { case STATE_RUNNING: case STATE_ASYNC_SUSPEND_REQUESTED: /* Maybe revisit this. But for now, don't allow nesting. */ if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE with BEGIN_NO_SAFEPOINTS. Can't nest no safepointing regions"); if (thread_state_cas (&info->thread_state, build_thread_state (cur_state, suspend_count, TRUE), raw_state) != raw_state) goto retry_state_change; trace_state_change_with_func ("BEGIN_NO_SAFEPOINTS", info, raw_state, cur_state, TRUE, 0, func); return; /* STATE_STARTING: STATE_DETACHED: STATE_SELF_SUSPENDED: STATE_ASYNC_SUSPENDED: STATE_BLOCKING: STATE_BLOCKING_ASYNC_SUSPENDED: STATE_BLOCKING_SELF_SUSPENDED: STATE_BLOCKING_SUSPEND_REQUESTED: no_safepoints only allowed for threads that are executing and GC Unsafe. */ default: mono_fatal_with_history ("Cannot transition thread %p from %s with BEGIN_NO_SAFEPOINTS", mono_thread_info_get_tid (info), state_name (cur_state)); } } /* Unset the no_safepoints flag on an executing GC Unsafe thread. The no_safepoints bit prevents polling (hence self-suspending) and transitioning from GC Unsafe to GC Safe. Thus the thread will not be (cooperatively) interrupted while the bit is set. We don't allow nesting no_safepoints regions, so the flag must be initially set. Since a suspend initiator may at any time request that a thread should suspend, ASYNC_SUSPEND_REQUESTED is allowed to have the no_safepoints bit set, too. (Future: We could augment this function to perform the transition and then return a return value that tells the thread to poll (and safepoint) if we enter here in the ASYNC_SUSPEND_REQUESTED state). */ void mono_threads_transition_end_no_safepoints (MonoThreadInfo *info, const char *func) { int raw_state, cur_state, suspend_count; gboolean no_safepoints; retry_state_change: UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, no_safepoints, info); switch (cur_state) { case STATE_RUNNING: case STATE_ASYNC_SUSPEND_REQUESTED: if (!no_safepoints) mono_fatal_with_history ("no_safepoints = FALSE, but should be TRUE with END_NO_SAFEPOINTS. Unbalanced no safepointing region"); if (thread_state_cas (&info->thread_state, build_thread_state (cur_state, suspend_count, FALSE), raw_state) != raw_state) goto retry_state_change; trace_state_change_with_func ("END_NO_SAFEPOINTS", info, raw_state, cur_state, FALSE, 0, func); return; /* STATE_STARTING: STATE_DETACHED: STATE_SELF_SUSPENDED: STATE_ASYNC_SUSPENDED: STATE_BLOCKING: STATE_BLOCKING_ASYNC_SUSPENDED: STATE_BLOCKING_SELF_SUSPENDED: STATE_BLOCKING_SUSPEND_REQUESTED: no_safepoints only allowed for threads that are executing and GC Unsafe. */ default: mono_fatal_with_history ("Cannot transition thread %p from %s with END_NO_SAFEPOINTS", mono_thread_info_get_tid (info), state_name (cur_state)); } } // State checking code /** * Return TRUE is the thread is in a runnable state. */ gboolean mono_thread_info_is_running (MonoThreadInfo *info) { switch (mono_thread_info_current_state (info)) { case STATE_RUNNING: case STATE_ASYNC_SUSPEND_REQUESTED: case STATE_BLOCKING_SUSPEND_REQUESTED: case STATE_BLOCKING: return TRUE; } return FALSE; } /** * Return TRUE is the thread is in an usable (suspendable) state */ gboolean mono_thread_info_is_live (MonoThreadInfo *info) { switch (mono_thread_info_current_state (info)) { case STATE_STARTING: case STATE_DETACHED: return FALSE; } return TRUE; } int mono_thread_info_suspend_count (MonoThreadInfo *info) { return info->thread_state.suspend_count; } int mono_thread_info_current_state (MonoThreadInfo *info) { return info->thread_state.state; } const char* mono_thread_state_name (int state) { return state_name (state); } gboolean mono_thread_is_gc_unsafe_mode (void) { MonoThreadInfo *cur = mono_thread_info_current (); if (!cur) return FALSE; switch (mono_thread_info_current_state (cur)) { case STATE_RUNNING: case STATE_ASYNC_SUSPEND_REQUESTED: return TRUE; default: return FALSE; } } gboolean mono_thread_info_will_not_safepoint (MonoThreadInfo *info) { return info->thread_state.no_safepoints; }
/** * \file */ #include <config.h> #include <mono/utils/mono-compiler.h> #include <mono/utils/mono-threads.h> #include <mono/utils/mono-tls.h> #include <mono/utils/mono-memory-model.h> #include <mono/utils/atomic.h> #include <mono/utils/checked-build.h> #include <mono/utils/mono-threads-debug.h> #include <errno.h> /*thread state helpers*/ static int get_thread_state (int thread_state) { const MonoThreadStateMachine state = {thread_state}; return state.state; } #if defined (THREADS_STATE_MACHINE_DEBUG_ENABLED) || defined (ENABLE_CHECKED_BUILD_THREAD) static int get_thread_suspend_count (int thread_state) { const MonoThreadStateMachine state = {thread_state}; return state.suspend_count; } #endif #ifdef THREADS_STATE_MACHINE_DEBUG_ENABLED static gboolean get_thread_no_safepoints (int thread_state) { const MonoThreadStateMachine state = {thread_state}; return state.no_safepoints; } #endif static MonoThreadStateMachine build_thread_state (int thread_state, int suspend_count, gboolean no_safepoints) { g_assert (suspend_count >= 0 && suspend_count <= THREAD_SUSPEND_COUNT_MAX); g_assert (thread_state >= 0 && thread_state <= STATE_MAX); no_safepoints = !!no_safepoints; // ensure it's 0 or 1 /* need a predictable value for the unused bits so that * thread_state_cas does not fail. */ MonoThreadStateMachine state = { 0 }; state.state = thread_state; state.no_safepoints = no_safepoints; state.suspend_count = suspend_count; return state; } static int thread_state_cas (MonoThreadStateMachine *state, MonoThreadStateMachine new_value, int old_raw) { return mono_atomic_cas_i32 (&state->raw, new_value.raw, old_raw); } static const char* state_name (int state) { static const char *state_names [] = { "STARTING", "DETACHED", "RUNNING", "ASYNC_SUSPENDED", "SELF_SUSPENDED", "ASYNC_SUSPEND_REQUESTED", "STATE_BLOCKING", "STATE_BLOCKING_ASYNC_SUSPENDED", "STATE_BLOCKING_SELF_SUSPENDED", "STATE_BLOCKING_SUSPEND_REQUESTED", }; return state_names [get_thread_state (state)]; } static void unwrap_thread_state (MonoThreadInfo* info, int *raw, int *cur, int *count, int *blk) { g_static_assert (sizeof (MonoThreadStateMachine) == sizeof (int32_t)); const MonoThreadStateMachine state = {mono_atomic_load_i32 (&info->thread_state.raw)}; // Read once from info and then read from local to get consistent values. *raw = state.raw; *cur = state.state; *count = state.suspend_count; *blk = state.no_safepoints; } #define UNWRAP_THREAD_STATE(RAW,CUR,COUNT,BLK,INFO) \ unwrap_thread_state ((INFO), &(RAW), &(CUR), &(COUNT), &(BLK)) static void check_thread_state (MonoThreadInfo* info) { #ifdef ENABLE_CHECKED_BUILD int raw_state, cur_state, suspend_count; gboolean no_safepoints; UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, no_safepoints, info); switch (cur_state) { case STATE_STARTING: case STATE_DETACHED: g_assert (!no_safepoints); /* fallthru */ case STATE_RUNNING: g_assert (suspend_count == 0); break; case STATE_BLOCKING_SELF_SUSPENDED: case STATE_BLOCKING_SUSPEND_REQUESTED: case STATE_BLOCKING_ASYNC_SUSPENDED: case STATE_ASYNC_SUSPENDED: case STATE_SELF_SUSPENDED: g_assert (!no_safepoints); /* fallthru */ case STATE_ASYNC_SUSPEND_REQUESTED: g_assert (suspend_count > 0); break; case STATE_BLOCKING: g_assert (!no_safepoints); g_assert (suspend_count == 0); break; default: g_error ("Invalid state %d", cur_state); } #endif } static void trace_state_change_with_func (const char *transition, MonoThreadInfo *info, int cur_raw_state, int next_state, gboolean next_no_safepoints, int suspend_count_delta, const char *func) { check_thread_state (info); THREADS_STATE_MACHINE_DEBUG ("[%s][%p] %s %s -> %s %s (%d -> %d) %s\n", transition, mono_thread_info_get_tid (info), state_name (get_thread_state (cur_raw_state)), (get_thread_no_safepoints (cur_raw_state) ? "X" : "."), state_name (next_state), (next_no_safepoints ? "X" : "."), get_thread_suspend_count (cur_raw_state), get_thread_suspend_count (cur_raw_state) + suspend_count_delta, func); CHECKED_BUILD_THREAD_TRANSITION (transition, info, get_thread_state (cur_raw_state), get_thread_suspend_count (cur_raw_state), next_state, suspend_count_delta); } static void trace_state_change_sigsafe (const char *transition, MonoThreadInfo *info, int cur_raw_state, int next_state, gboolean next_no_safepoints, int suspend_count_delta, const char *func) { check_thread_state (info); THREADS_STATE_MACHINE_DEBUG ("[%s][%p] %s %s -> %s %s (%d -> %d) %s\n", transition, mono_thread_info_get_tid (info), state_name (get_thread_state (cur_raw_state)), (get_thread_no_safepoints (cur_raw_state) ? "X" : "."), state_name (next_state), (next_no_safepoints ? "X" : "."), get_thread_suspend_count (cur_raw_state), get_thread_suspend_count (cur_raw_state) + suspend_count_delta, func); CHECKED_BUILD_THREAD_TRANSITION_NOBT (transition, info, get_thread_state (cur_raw_state), get_thread_suspend_count (cur_raw_state), next_state, suspend_count_delta); } static void trace_state_change (const char *transition, MonoThreadInfo *info, int cur_raw_state, int next_state, gboolean next_no_safepoints, int suspend_count_delta) // FIXME migrate all uses { trace_state_change_with_func (transition, info, cur_raw_state, next_state, next_no_safepoints, suspend_count_delta, ""); } /* This is the transition that signals that a thread is functioning. Its main goal is to catch threads been witnessed before been fully registered. */ void mono_threads_transition_attach (MonoThreadInfo* info) { int raw_state, cur_state, suspend_count; gboolean no_safepoints; retry_state_change: UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, no_safepoints, info); switch (cur_state) { case STATE_STARTING: if (!(suspend_count == 0)) mono_fatal_with_history ("suspend_count = %d, but should be == 0", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (thread_state_cas (&info->thread_state, build_thread_state (STATE_RUNNING, 0, 0), raw_state) != raw_state) goto retry_state_change; trace_state_change ("ATTACH", info, raw_state, STATE_RUNNING, FALSE, 0); break; default: mono_fatal_with_history ("Cannot transition current thread from %s with ATTACH", state_name (cur_state)); } } /* This is the transition that signals that a thread is no longer registered with the runtime. Its main goal is to catch threads been witnessed after they detach. This returns TRUE is the transition succeeded. If it returns false it means that there's a pending suspend that should be acted upon. */ gboolean mono_threads_transition_detach (MonoThreadInfo *info) { int raw_state, cur_state, suspend_count; gboolean no_safepoints; retry_state_change: UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, no_safepoints, info); switch (cur_state) { case STATE_RUNNING: case STATE_BLOCKING: /* An OS thread on coop goes STARTING->BLOCKING->RUNNING->BLOCKING->DETACHED */ if (!(suspend_count == 0)) mono_fatal_with_history ("suspend_count = %d, but should be == 0", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (thread_state_cas (&info->thread_state, build_thread_state (STATE_DETACHED, 0, 0), raw_state) != raw_state) goto retry_state_change; trace_state_change ("DETACH", info, raw_state, STATE_DETACHED, FALSE, 0); return TRUE; case STATE_ASYNC_SUSPEND_REQUESTED: //Can't detach until whoever asked us to suspend to be happy with us case STATE_BLOCKING_SUSPEND_REQUESTED: return FALSE; /* STATE_ASYNC_SUSPENDED: Code should not be running while suspended. STATE_SELF_SUSPENDED: Code should not be running while suspended. STATE_BLOCKING_SELF_SUSPENDED: This is a bug in coop x suspend that resulted the thread in an undetachable state. STATE_BLOCKING_ASYNC_SUSPENDED: Same as BLOCKING_SELF_SUSPENDED */ default: mono_fatal_with_history ("Cannot transition current thread %p from %s with DETACH", info, state_name (cur_state)); } } /* This transition initiates the suspension of another thread. Returns one of the following values: - ReqSuspendInitSuspendRunning: Thread suspend requested, caller must initiate suspend. - ReqSuspendInitSuspendBlocking: Thread in blocking state, caller may initiate suspend. - ReqSuspendAlreadySuspended: Thread was already suspended and not executing, nothing to do. - ReqSuspendAlreadySuspendedBlocking: Thread was already in blocking and a suspend was requested and the thread is still executing (perhaps in a syscall), nothing to do. */ MonoRequestSuspendResult mono_threads_transition_request_suspension (MonoThreadInfo *info) { int raw_state, cur_state, suspend_count; gboolean no_safepoints; g_assert (info != mono_thread_info_current ()); retry_state_change: UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, no_safepoints, info); switch (cur_state) { case STATE_RUNNING: //Post an async suspend request if (!(suspend_count == 0)) mono_fatal_with_history ("suspend_count = %d, but should be == 0", suspend_count); if (thread_state_cas (&info->thread_state, build_thread_state (STATE_ASYNC_SUSPEND_REQUESTED, 1, no_safepoints), raw_state) != raw_state) goto retry_state_change; trace_state_change ("SUSPEND_INIT_REQUESTED", info, raw_state, STATE_ASYNC_SUSPEND_REQUESTED, no_safepoints, 1); return ReqSuspendInitSuspendRunning; //This is the first async suspend request against the target case STATE_BLOCKING_SELF_SUSPENDED: case STATE_BLOCKING_ASYNC_SUSPENDED: case STATE_ASYNC_SUSPENDED: case STATE_SELF_SUSPENDED: if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (!(suspend_count > 0 && suspend_count < THREAD_SUSPEND_COUNT_MAX)) mono_fatal_with_history ("suspend_count = %d, but should be > 0 and < THREAD_SUSPEND_COUNT_MAX", suspend_count); if (thread_state_cas (&info->thread_state, build_thread_state (cur_state, suspend_count + 1, no_safepoints), raw_state) != raw_state) goto retry_state_change; trace_state_change ("SUSPEND_INIT_REQUESTED", info, raw_state, cur_state, no_safepoints, 1); return ReqSuspendAlreadySuspended; //Thread is already suspended so we don't need to wait it to suspend case STATE_BLOCKING: if (!(suspend_count == 0)) mono_fatal_with_history ("suspend_count = %d, but should be == 0", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (thread_state_cas (&info->thread_state, build_thread_state (STATE_BLOCKING_SUSPEND_REQUESTED, 1, no_safepoints), raw_state) != raw_state) goto retry_state_change; trace_state_change ("SUSPEND_INIT_REQUESTED", info, raw_state, STATE_BLOCKING_SUSPEND_REQUESTED, no_safepoints, 1); return ReqSuspendInitSuspendBlocking; //A thread in the blocking state has its state saved so we can treat it as suspended. case STATE_BLOCKING_SUSPEND_REQUESTED: /* This should only be happening if we're doing a cooperative suspend of a blocking thread. * In which case we could be in BLOCKING_SUSPEND_REQUESTED until we execute a done or abort blocking. * In preemptive suspend of a blocking thread since there's a single suspend initiator active at a time, * we would expect a finish_async_suspension or a done/abort blocking before the next suspension request */ if (!(suspend_count > 0 && suspend_count < THREAD_SUSPEND_COUNT_MAX)) mono_fatal_with_history ("suspend_count = %d, but should be > 0 and < THREAD_SUSPEND_COUNT_MAX", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (thread_state_cas (&info->thread_state, build_thread_state (cur_state, suspend_count + 1, no_safepoints), raw_state) != raw_state) goto retry_state_change; trace_state_change ("SUSPEND_INIT_REQUESTED", info, raw_state, cur_state, no_safepoints, 1); return ReqSuspendAlreadySuspendedBlocking; /* [1] It's questionable on what to do if we hit the beginning of a self suspend. The expected behavior is that the target should poll its state very soon so the the suspend latency should be minimal. STATE_ASYNC_SUSPEND_REQUESTED: Since there can only be one async suspend in progress and it must finish, it should not be possible to witness this. */ default: mono_fatal_with_history ("Cannot transition thread %p from %s with SUSPEND_INIT_REQUESTED", mono_thread_info_get_tid (info), state_name (cur_state)); } return (MonoRequestSuspendResult) FALSE; } /* Peek at the thread state and return whether it's BLOCKING_SUSPEND_REQUESTED or not. Assumes that it is called in the second phase of a two-phase suspend, so the thread is either some flavor of suspended or else blocking suspend requested. All other states can't happen. */ gboolean mono_threads_transition_peek_blocking_suspend_requested (MonoThreadInfo *info) { int raw_state, cur_state, suspend_count; gboolean no_safepoints; g_assert (info != mono_thread_info_current ()); UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, no_safepoints, info); switch (cur_state) { case STATE_ASYNC_SUSPENDED: case STATE_SELF_SUSPENDED: return FALSE; /*ReqPeekBlockingSuspendRequestedRunningSuspended;*/ case STATE_BLOCKING_SELF_SUSPENDED: case STATE_BLOCKING_ASYNC_SUSPENDED: case STATE_BLOCKING_SUSPEND_REQUESTED: if (!(suspend_count > 0 && suspend_count < THREAD_SUSPEND_COUNT_MAX)) mono_fatal_with_history ("suspend_count = %d, but should be > 0 and < THREAD_SUSPEND_COUNT_MAX", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (cur_state == STATE_BLOCKING_SUSPEND_REQUESTED) return TRUE; /*ReqPeekBlockingSuspendRequestedBlockingSuspendRequested;*/ else return FALSE; /*ReqPeekBlockingSuspendRequestedBlockingSuspended;*/ /* STATE_RUNNING: Can't happen - should have been suspended in the first phase. STATE_ASYNC_SUSPEND_REQUESTED Can't happen - first phase should've waited until the thread self-suspended STATE_BLOCKING: Can't happen - should've had a suspension request in the first phase. */ default: mono_fatal_with_history ("Thread %p in unexpected state %s with PEEK_BLOCKING_SUSPEND_REQUESTED", mono_thread_info_get_tid (info), state_name (cur_state)); } } /* Check the current state of the thread and try to init a self suspend. This must be called with self state saved. Returns one of the following values: - Resumed: Async resume happened and current thread should keep running - Suspend: Caller should wait for a resume signal - SelfSuspendNotifyAndWait: Notify the suspend initiator and wait for a resume signals suspend should start. */ MonoSelfSupendResult mono_threads_transition_state_poll (MonoThreadInfo *info) { int raw_state, cur_state, suspend_count; gboolean no_safepoints; g_assert (mono_thread_info_is_current (info)); retry_state_change: UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, no_safepoints, info); switch (cur_state) { case STATE_RUNNING: if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE in RUNNING with STATE_POLL"); if (!(suspend_count == 0)) mono_fatal_with_history ("suspend_count = %d, but should be == 0", suspend_count); trace_state_change ("STATE_POLL", info, raw_state, cur_state, no_safepoints, 0); return SelfSuspendResumed; //We're fine, don't suspend case STATE_ASYNC_SUSPEND_REQUESTED: //Async suspend requested, service it with a self suspend if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE in ASYNS_SUSPEND_REQUESTED with STATE_POLL"); if (!(suspend_count > 0)) mono_fatal_with_history ("suspend_count = %d, but should be > 0", suspend_count); if (thread_state_cas (&info->thread_state, build_thread_state (STATE_SELF_SUSPENDED, suspend_count, no_safepoints), raw_state) != raw_state) goto retry_state_change; trace_state_change ("STATE_POLL", info, raw_state, STATE_SELF_SUSPENDED, no_safepoints, 0); return SelfSuspendNotifyAndWait; //Caller should notify suspend initiator and wait for resume /* STATE_ASYNC_SUSPENDED: Code should not be running while suspended. STATE_SELF_SUSPENDED: Code should not be running while suspended. STATE_BLOCKING: STATE_BLOCKING_SUSPEND_REQUESTED: STATE_BLOCKING_ASYNC_SUSPENDED: STATE_BLOCKING_SELF_SUSPENDED: Poll is a local state transition. No VM activities are allowed while in blocking mode. (In all the blocking states - the local thread has no checkpoints, hence no polling, it can only do abort blocking or done blocking on itself). */ default: mono_fatal_with_history ("Cannot transition thread %p from %s with STATE_POLL", mono_thread_info_get_tid (info), state_name (cur_state)); } } /* Try to resume a suspended thread. Returns one of the following values: - Sucess: The thread was resumed. - Error: The thread was not suspended in the first place. [2] - InitSelfResume: The thread is blocked on self suspend and should be resumed - InitAsyncResume: The thread is blocked on async suspend and should be resumed - ResumeInitBlockingResume: The thread was suspended on the exit path of blocking state and should be resumed FIXME: ResumeInitBlockingResume is just InitSelfResume by a different name. [2] This threading system uses an unsigned suspend count. Which means a resume cannot be used as a suspend permit and cancel each other. Suspend permits are really useful to implement managed synchronization structures that don't consume native resources. The downside is that they further complicate the design of this system as the RUNNING state now has a non zero suspend counter. It can be implemented in the future if we find resume/suspend races that cannot be (efficiently) fixed by other means. One major issue with suspend permits is runtime facilities (GC, debugger) that must have the target suspended when requested. This would make permits really harder to add. */ MonoResumeResult mono_threads_transition_request_resume (MonoThreadInfo* info) { int raw_state, cur_state, suspend_count; gboolean no_safepoints; g_assert (info != mono_thread_info_current ()); //One can't self resume [3] retry_state_change: UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, no_safepoints, info); switch (cur_state) { case STATE_RUNNING: //Thread already running. if (!(suspend_count == 0)) mono_fatal_with_history ("suspend_count = %d, but should be == 0", suspend_count); trace_state_change ("RESUME", info, raw_state, cur_state, no_safepoints, 0); return ResumeError; //Resume failed because thread was not blocked case STATE_BLOCKING: //Blocking, might have a suspend count, we decrease if it's > 0 if (!(suspend_count == 0)) mono_fatal_with_history ("suspend_count = %d, but should be == 0", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); trace_state_change ("RESUME", info, raw_state, cur_state, no_safepoints, 0); return ResumeError; case STATE_BLOCKING_SUSPEND_REQUESTED: if (!(suspend_count > 0)) mono_fatal_with_history ("suspend_count = %d, but should be > 0", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (suspend_count > 1) { if (thread_state_cas (&info->thread_state, build_thread_state (cur_state, suspend_count - 1, no_safepoints), raw_state) != raw_state) goto retry_state_change; trace_state_change ("RESUME", info, raw_state, cur_state, no_safepoints, -1); return ResumeOk; //Resume worked and there's nothing for the caller to do. } else { if (thread_state_cas (&info->thread_state, build_thread_state (STATE_BLOCKING, 0, 0), raw_state) != raw_state) goto retry_state_change; trace_state_change ("RESUME", info, raw_state, STATE_BLOCKING, no_safepoints, -1); return ResumeOk; // Resume worked, back in blocking, nothing for the caller to do. } case STATE_BLOCKING_ASYNC_SUSPENDED: if (!(suspend_count > 0)) mono_fatal_with_history ("suspend_count = %d, but should be > 0", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (suspend_count > 1) { if (thread_state_cas (&info->thread_state, build_thread_state (cur_state, suspend_count - 1, no_safepoints), raw_state) != raw_state) goto retry_state_change; trace_state_change ("RESUME", info, raw_state, cur_state, no_safepoints, -1); return ResumeOk; // Resume worked, there's nothing else for the caller to do. } else { if (thread_state_cas (&info->thread_state, build_thread_state (STATE_BLOCKING, 0, 0), raw_state) != raw_state) goto retry_state_change; trace_state_change ("RESUME", info, raw_state, STATE_BLOCKING, no_safepoints, -1); return ResumeInitAsyncResume; // Resume worked and caller must do async resume, thread resumes in BLOCKING } case STATE_BLOCKING_SELF_SUSPENDED: //Decrease the suspend_count and maybe resume case STATE_ASYNC_SUSPENDED: case STATE_SELF_SUSPENDED: if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (!(suspend_count > 0)) mono_fatal_with_history ("suspend_count = %d, but should be > 0", suspend_count); if (suspend_count > 1) { if (thread_state_cas (&info->thread_state, build_thread_state (cur_state, suspend_count - 1, no_safepoints), raw_state) != raw_state) goto retry_state_change; trace_state_change ("RESUME", info, raw_state, cur_state, no_safepoints, -1); return ResumeOk; //Resume worked and there's nothing for the caller to do. } else { if (thread_state_cas (&info->thread_state, build_thread_state (STATE_RUNNING, 0, no_safepoints), raw_state) != raw_state) goto retry_state_change; trace_state_change ("RESUME", info, raw_state, STATE_RUNNING, no_safepoints, -1); if (cur_state == STATE_ASYNC_SUSPENDED) return ResumeInitAsyncResume; //Resume worked and caller must do async resume else if (cur_state == STATE_SELF_SUSPENDED) return ResumeInitSelfResume; //Resume worked and caller must do self resume else return ResumeInitBlockingResume; //Resume worked and caller must do blocking resume } /* STATE_ASYNC_SUSPEND_REQUESTED: Only one async suspend/resume operation can be in flight, so a resume cannot witness an internal state of suspend [3] A self-resume makes no sense given it requires the thread to be running, which means its suspend count must be zero. A self resume would make sense as a suspend permit, but as explained in [2] we don't support it so this is a bug. [4] It's questionable on whether a resume (an async operation) should be able to cancel a self suspend. The scenario where this would happen is similar to the one described in [2] when this is used for as a synchronization primitive. If this turns to be a problem we should either implement [2] or make this an invalid transition. */ default: mono_fatal_with_history ("Cannot transition thread %p from %s with REQUEST_RESUME", mono_thread_info_get_tid (info), state_name (cur_state)); } } /* Try to resume a suspended thread and atomically request that it suspend again. Returns one of the following values: - InitAsyncPulse: The thread is suspended with preemptive suspend and should be resumed. */ MonoPulseResult mono_threads_transition_request_pulse (MonoThreadInfo* info) { int raw_state, cur_state, suspend_count; gboolean no_safepoints; g_assert (info != mono_thread_info_current ()); //One can't self pulse [3] retry_state_change: UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, no_safepoints, info); switch (cur_state) { case STATE_BLOCKING_ASYNC_SUSPENDED: if (!(suspend_count == 1)) mono_fatal_with_history ("suspend_count = %d, but should be == 1", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (thread_state_cas (&info->thread_state, build_thread_state (STATE_BLOCKING_SUSPEND_REQUESTED, suspend_count, no_safepoints), raw_state) != raw_state) goto retry_state_change; trace_state_change ("PULSE", info, raw_state, STATE_BLOCKING_SUSPEND_REQUESTED, no_safepoints, -1); return PulseInitAsyncPulse; // Pulse worked and caller must do async pulse, thread pulses in BLOCKING /* STATE_RUNNING: STATE_BLOCKING: Only one suspend initiator at a time. Current STW stopped the thread and now needs to resume it. So thread must be in one of the suspended states if we get here. STATE_BLOCKING_SUSPEND_REQUESTED: STATE_ASYNC_SUSPEND_REQUESTED: Only one pulse operation can be in flight, so a pulse cannot witness an internal state of suspend STATE_ASYNC_SUSPENDED: Hybrid suspend shouldn't put GC Unsafe threads into async suspended state. STATE_BLOCKING_SELF_SUSPENDED: STATE_SELF_SUSPENDED: Don't expect these to be pulsed - they're not problematic. */ default: mono_fatal_with_history ("Cannot transition thread %p from %s with REQUEST_PULSE", mono_thread_info_get_tid (info), state_name (cur_state)); } } /* Abort last step of preemptive suspend in case of failure to async suspend thread. This function makes sure state machine reflects current state of thread (running/suspended) in case of failure to complete async suspend of thread. NOTE, thread can still have reached a suspend state (in case of self-suspend). Returns TRUE if async suspend request was successfully aborted. Thread should be in STATE_RUNNING. Returns FALSE if async suspend request was successfully aborted but thread already reached self-suspended. */ gboolean mono_threads_transition_abort_async_suspend (MonoThreadInfo* info) { int raw_state, cur_state, suspend_count; gboolean no_safepoints; retry_state_change: UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, no_safepoints, info); switch (cur_state) { case STATE_SELF_SUSPENDED: //async suspend raced with self suspend and lost case STATE_BLOCKING_SELF_SUSPENDED: //async suspend raced with blocking and lost if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); trace_state_change_sigsafe ("ABORT_ASYNC_SUSPEND", info, raw_state, cur_state, no_safepoints, 0, ""); return FALSE; //thread successfully reached suspend state. case STATE_ASYNC_SUSPEND_REQUESTED: case STATE_BLOCKING_SUSPEND_REQUESTED: if (!(suspend_count > 0)) mono_fatal_with_history ("suspend_count = %d, but should be > 0", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (suspend_count > 1) { if (thread_state_cas (&info->thread_state, build_thread_state (cur_state, suspend_count - 1, no_safepoints), raw_state) != raw_state) goto retry_state_change; trace_state_change ("ABORT_ASYNC_SUSPEND", info, raw_state, cur_state, no_safepoints, -1); } else { if (thread_state_cas (&info->thread_state, build_thread_state (STATE_RUNNING, 0, no_safepoints), raw_state) != raw_state) goto retry_state_change; trace_state_change ("ABORT_ASYNC_SUSPEND", info, raw_state, STATE_RUNNING, no_safepoints, -1); } return TRUE; //aborting thread suspend request succeded, thread is running. /* STATE_RUNNING: A thread cannot escape suspension once requested. STATE_ASYNC_SUSPENDED: There can be only one suspend initiator at a given time, meaning this state should have been visible on the first stage of suspend. STATE_BLOCKING: If a thread is subject to preemptive suspend, there is no race as the resume initiator should have suspended the thread to STATE_BLOCKING_ASYNC_SUSPENDED or STATE_BLOCKING_SELF_SUSPENDED before resuming. With cooperative suspend, there are no finish_async_suspend transitions since there's no path back from asyns_suspend requested to running. STATE_BLOCKING_ASYNC_SUSPENDED: There can only be one suspend initiator at a given time, meaning this state should have ben visible on the first stage of suspend. */ default: mono_fatal_with_history ("Cannot transition thread %p from %s with ABORT_ASYNC_SUSPEND", mono_thread_info_get_tid (info), state_name (cur_state)); } } /* This performs the last step of preemptive suspend. Returns TRUE if the caller should wait for resume. */ gboolean mono_threads_transition_finish_async_suspend (MonoThreadInfo* info) { int raw_state, cur_state, suspend_count; gboolean no_safepoints; retry_state_change: UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, no_safepoints, info); switch (cur_state) { case STATE_SELF_SUSPENDED: //async suspend raced with self suspend and lost case STATE_BLOCKING_SELF_SUSPENDED: //async suspend raced with blocking and lost if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); trace_state_change_sigsafe ("FINISH_ASYNC_SUSPEND", info, raw_state, cur_state, no_safepoints, 0, ""); return FALSE; //let self suspend wait case STATE_ASYNC_SUSPEND_REQUESTED: if (!(suspend_count > 0)) mono_fatal_with_history ("suspend_count = %d, but should be > 0", suspend_count); /* Don't expect to see no_safepoints, ever, with async */ if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE in ASYNC_SUSPEND_REQUESTED with FINISH_ASYNC_SUSPEND"); if (thread_state_cas (&info->thread_state, build_thread_state (STATE_ASYNC_SUSPENDED, suspend_count, FALSE), raw_state) != raw_state) goto retry_state_change; trace_state_change_sigsafe ("FINISH_ASYNC_SUSPEND", info, raw_state, STATE_ASYNC_SUSPENDED, FALSE, 0, ""); return TRUE; //Async suspend worked, now wait for resume case STATE_BLOCKING_SUSPEND_REQUESTED: if (!(suspend_count > 0)) mono_fatal_with_history ("suspend_count = %d, but should be > 0", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (thread_state_cas (&info->thread_state, build_thread_state (STATE_BLOCKING_ASYNC_SUSPENDED, suspend_count, FALSE), raw_state) != raw_state) goto retry_state_change; trace_state_change_sigsafe ("FINISH_ASYNC_SUSPEND", info, raw_state, STATE_BLOCKING_ASYNC_SUSPENDED, FALSE, 0, ""); return TRUE; //Async suspend of blocking thread worked, now wait for resume /* STATE_RUNNING: A thread cannot escape suspension once requested. STATE_ASYNC_SUSPENDED: There can be only one suspend initiator at a given time, meaning this state should have been visible on the first stage of suspend. STATE_BLOCKING: If a thread is subject to preemptive suspend, there is no race as the resume initiator should have suspended the thread to STATE_BLOCKING_ASYNC_SUSPENDED or STATE_BLOCKING_SELF_SUSPENDED before resuming. With cooperative suspend, there are no finish_async_suspend transitions since there's no path back from asyns_suspend requested to running. STATE_BLOCKING_ASYNC_SUSPENDED: There can only be one suspend initiator at a given time, meaning this state should have ben visible on the first stage of suspend. */ default: mono_fatal_with_history ("Cannot transition thread %p from %s with FINISH_ASYNC_SUSPEND", mono_thread_info_get_tid (info), state_name (cur_state)); } } /* This transitions the thread into a cooperative state where it's assumed to be suspended but can continue. Native runtime code might want to put itself into a state where the thread is considered suspended but can keep running. That state only works as long as the only managed state touched is blitable and was pinned before the transition. It returns the action the caller must perform: - Continue: Entered blocking state sucessfully; - PollAndRetry: Async suspend raced and won, try to suspend and then retry; */ MonoDoBlockingResult mono_threads_transition_do_blocking (MonoThreadInfo* info, const char *func) { int raw_state, cur_state, suspend_count; gboolean no_safepoints; retry_state_change: UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, no_safepoints, info); switch (cur_state) { case STATE_RUNNING: //transition to blocked if (!(suspend_count == 0)) mono_fatal_with_history ("suspend_count = %d, but should be == 0", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE in state RUNNING with DO_BLOCKING"); if (thread_state_cas (&info->thread_state, build_thread_state (STATE_BLOCKING, suspend_count, no_safepoints), raw_state) != raw_state) goto retry_state_change; trace_state_change ("DO_BLOCKING", info, raw_state, STATE_BLOCKING, no_safepoints, 0); return DoBlockingContinue; case STATE_ASYNC_SUSPEND_REQUESTED: if (!(suspend_count > 0)) mono_fatal_with_history ("suspend_count = %d, but should be > 0", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE in state ASYNC_SUSPEND_REQUESTED with DO_BLOCKING"); trace_state_change ("DO_BLOCKING", info, raw_state, cur_state, no_safepoints, 0); return DoBlockingPollAndRetry; /* STATE_ASYNC_SUSPENDED STATE_SELF_SUSPENDED: Code should not be running while suspended. STATE_BLOCKING: STATE_BLOCKING_SUSPEND_REQUESTED: STATE_BLOCKING_SELF_SUSPENDED: Blocking is not nestabled STATE_BLOCKING_ASYNC_SUSPENDED: Blocking is not nestable _and_ code should not be running while suspended */ default: mono_fatal_with_history ("%s Cannot transition thread %p from %s with DO_BLOCKING", func, mono_thread_info_get_tid (info), state_name (cur_state)); } } /* This is the exit transition from the blocking state. If this thread is logically async suspended it will have to wait until its resumed before continuing. It returns one of: -Ok: Done with blocking, just move on; -Wait: This thread was suspended while in blocking, wait for resume. */ MonoDoneBlockingResult mono_threads_transition_done_blocking (MonoThreadInfo* info, const char *func) { int raw_state, cur_state, suspend_count; gboolean no_safepoints; retry_state_change: UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, no_safepoints, info); switch (cur_state) { case STATE_BLOCKING: if (!(suspend_count == 0)) mono_fatal_with_history ("%s suspend_count = %d, but should be == 0", func, suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (thread_state_cas (&info->thread_state, build_thread_state (STATE_RUNNING, suspend_count, no_safepoints), raw_state) != raw_state) goto retry_state_change; trace_state_change_sigsafe ("DONE_BLOCKING", info, raw_state, STATE_RUNNING, no_safepoints, 0, func); return DoneBlockingOk; case STATE_BLOCKING_SUSPEND_REQUESTED: if (!(suspend_count > 0)) mono_fatal_with_history ("suspend_count = %d, but should be > 0", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (thread_state_cas (&info->thread_state, build_thread_state (STATE_BLOCKING_SELF_SUSPENDED, suspend_count, no_safepoints), raw_state) != raw_state) goto retry_state_change; trace_state_change_with_func ("DONE_BLOCKING", info, raw_state, STATE_BLOCKING_SELF_SUSPENDED, no_safepoints, 0, func); return DoneBlockingWait; /* STATE_RUNNING: //Blocking was aborted and not properly restored STATE_ASYNC_SUSPEND_REQUESTED: //Blocking was aborted, not properly restored and now there's a pending suspend STATE_ASYNC_SUSPENDED STATE_SELF_SUSPENDED: Code should not be running while suspended. STATE_BLOCKING_SELF_SUSPENDED: This an exit state of done blocking STATE_BLOCKING_ASYNC_SUSPENDED: This is an exit state of done blocking */ default: mono_fatal_with_history ("Cannot transition thread %p from %s with DONE_BLOCKING", mono_thread_info_get_tid (info), state_name (cur_state)); } } /* Transition a thread in what should be a blocking state back to running state. This is different that done blocking because the goal is to get back to blocking once we're done. This is required to be able to bail out of blocking in case we're back to inside the runtime. It returns one of: -Ignore: Thread was not in blocking, nothing to do; -IgnoreAndPoll: Thread was not blocking and there's a pending suspend that needs to be processed; -Ok: Blocking state successfully aborted; -Wait: Blocking state successfully aborted, there's a pending suspend to be processed though, wait for resume. */ MonoAbortBlockingResult mono_threads_transition_abort_blocking (THREAD_INFO_TYPE* info, const char *func) { int raw_state, cur_state, suspend_count; gboolean no_safepoints; retry_state_change: UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, no_safepoints, info); switch (cur_state) { case STATE_RUNNING: //thread already in runnable state /* Even though we're going to ignore this transition, still * assert about no_safepoints. Rationale: make it easier to catch * cases where we would be in ASYNC_SUSPEND_REQUESTED with * no_safepoints set, since those are polling points. */ if (no_safepoints) { /* reset the state to no safepoints and then abort. If a * thread asserts somewhere because no_safepoints was set when it * shouldn't have been, we would get a second assertion here while * unwinding if we hadn't reset the no_safepoints flag. */ if (thread_state_cas (&info->thread_state, build_thread_state (STATE_RUNNING, suspend_count, FALSE), raw_state) != raw_state) goto retry_state_change; /* record the current transition, in order to grab a backtrace */ trace_state_change_with_func ("ABORT_BLOCKING", info, raw_state, STATE_RUNNING, FALSE, 0, func); mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE in state RUNNING with ABORT_BLOCKING"); } trace_state_change_sigsafe ("ABORT_BLOCKING", info, raw_state, cur_state, no_safepoints, 0, func); return AbortBlockingIgnore; case STATE_ASYNC_SUSPEND_REQUESTED: //thread is runnable and have a pending suspend if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE in state ASYNC_SUSPEND_REQUESTED with ABORT_BLOCKING"); trace_state_change_sigsafe ("ABORT_BLOCKING", info, raw_state, cur_state, no_safepoints, 0, func); return AbortBlockingIgnoreAndPoll; case STATE_BLOCKING: if (!(suspend_count == 0)) mono_fatal_with_history ("suspend_count = %d, but should be == 0", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (thread_state_cas (&info->thread_state, build_thread_state (STATE_RUNNING, suspend_count, FALSE), raw_state) != raw_state) goto retry_state_change; trace_state_change_sigsafe ("ABORT_BLOCKING", info, raw_state, STATE_RUNNING, FALSE, 0, func); return AbortBlockingOk; case STATE_BLOCKING_SUSPEND_REQUESTED: if (!(suspend_count > 0)) mono_fatal_with_history ("suspend_count = %d, but should be > 0", suspend_count); if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE"); if (thread_state_cas (&info->thread_state, build_thread_state (STATE_BLOCKING_SELF_SUSPENDED, suspend_count, FALSE), raw_state) != raw_state) goto retry_state_change; trace_state_change_with_func ("ABORT_BLOCKING", info, raw_state, STATE_BLOCKING_SELF_SUSPENDED, FALSE, 0, func); return AbortBlockingWait; /* STATE_ASYNC_SUSPENDED: STATE_SELF_SUSPENDED: Code should not be running while suspended. STATE_BLOCKING_SELF_SUSPENDED: This is an exit state of done blocking, can't happen here. STATE_BLOCKING_ASYNC_SUSPENDED: This is an exit state of abort blocking, can't happen here. */ default: mono_fatal_with_history ("Cannot transition thread %p from %s with ABORT_BLOCKING", mono_thread_info_get_tid (info), state_name (cur_state)); } } /* Set the no_safepoints flag on an executing GC Unsafe thread. The no_safepoints bit prevents polling (hence self-suspending) and transitioning from GC Unsafe to GC Safe. Thus the thread will not be (cooperatively) interrupted while the bit is set. We don't allow nesting no_safepoints regions, so the flag must be initially unset. Since a suspend initiator may at any time request that a thread should suspend, ASYNC_SUSPEND_REQUESTED is allowed to have the no_safepoints bit set, too. (Future: We could augment this function to return a return value that tells the thread to poll and retry the transition since if we enter here in the ASYNC_SUSPEND_REQUESTED state). */ void mono_threads_transition_begin_no_safepoints (MonoThreadInfo *info, const char *func) { int raw_state, cur_state, suspend_count; gboolean no_safepoints; retry_state_change: UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, no_safepoints, info); switch (cur_state) { case STATE_RUNNING: case STATE_ASYNC_SUSPEND_REQUESTED: /* Maybe revisit this. But for now, don't allow nesting. */ if (no_safepoints) mono_fatal_with_history ("no_safepoints = TRUE, but should be FALSE with BEGIN_NO_SAFEPOINTS. Can't nest no safepointing regions"); if (thread_state_cas (&info->thread_state, build_thread_state (cur_state, suspend_count, TRUE), raw_state) != raw_state) goto retry_state_change; trace_state_change_with_func ("BEGIN_NO_SAFEPOINTS", info, raw_state, cur_state, TRUE, 0, func); return; /* STATE_STARTING: STATE_DETACHED: STATE_SELF_SUSPENDED: STATE_ASYNC_SUSPENDED: STATE_BLOCKING: STATE_BLOCKING_ASYNC_SUSPENDED: STATE_BLOCKING_SELF_SUSPENDED: STATE_BLOCKING_SUSPEND_REQUESTED: no_safepoints only allowed for threads that are executing and GC Unsafe. */ default: mono_fatal_with_history ("Cannot transition thread %p from %s with BEGIN_NO_SAFEPOINTS", mono_thread_info_get_tid (info), state_name (cur_state)); } } /* Unset the no_safepoints flag on an executing GC Unsafe thread. The no_safepoints bit prevents polling (hence self-suspending) and transitioning from GC Unsafe to GC Safe. Thus the thread will not be (cooperatively) interrupted while the bit is set. We don't allow nesting no_safepoints regions, so the flag must be initially set. Since a suspend initiator may at any time request that a thread should suspend, ASYNC_SUSPEND_REQUESTED is allowed to have the no_safepoints bit set, too. (Future: We could augment this function to perform the transition and then return a return value that tells the thread to poll (and safepoint) if we enter here in the ASYNC_SUSPEND_REQUESTED state). */ void mono_threads_transition_end_no_safepoints (MonoThreadInfo *info, const char *func) { int raw_state, cur_state, suspend_count; gboolean no_safepoints; retry_state_change: UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, no_safepoints, info); switch (cur_state) { case STATE_RUNNING: case STATE_ASYNC_SUSPEND_REQUESTED: if (!no_safepoints) mono_fatal_with_history ("no_safepoints = FALSE, but should be TRUE with END_NO_SAFEPOINTS. Unbalanced no safepointing region"); if (thread_state_cas (&info->thread_state, build_thread_state (cur_state, suspend_count, FALSE), raw_state) != raw_state) goto retry_state_change; trace_state_change_with_func ("END_NO_SAFEPOINTS", info, raw_state, cur_state, FALSE, 0, func); return; /* STATE_STARTING: STATE_DETACHED: STATE_SELF_SUSPENDED: STATE_ASYNC_SUSPENDED: STATE_BLOCKING: STATE_BLOCKING_ASYNC_SUSPENDED: STATE_BLOCKING_SELF_SUSPENDED: STATE_BLOCKING_SUSPEND_REQUESTED: no_safepoints only allowed for threads that are executing and GC Unsafe. */ default: mono_fatal_with_history ("Cannot transition thread %p from %s with END_NO_SAFEPOINTS", mono_thread_info_get_tid (info), state_name (cur_state)); } } // State checking code /** * Return TRUE is the thread is in a runnable state. */ gboolean mono_thread_info_is_running (MonoThreadInfo *info) { switch (mono_thread_info_current_state (info)) { case STATE_RUNNING: case STATE_ASYNC_SUSPEND_REQUESTED: case STATE_BLOCKING_SUSPEND_REQUESTED: case STATE_BLOCKING: return TRUE; } return FALSE; } /** * Return TRUE is the thread is in an usable (suspendable) state */ gboolean mono_thread_info_is_live (MonoThreadInfo *info) { switch (mono_thread_info_current_state (info)) { case STATE_STARTING: case STATE_DETACHED: return FALSE; } return TRUE; } int mono_thread_info_suspend_count (MonoThreadInfo *info) { return info->thread_state.suspend_count; } int mono_thread_info_current_state (MonoThreadInfo *info) { return info->thread_state.state; } const char* mono_thread_state_name (int state) { return state_name (state); } gboolean mono_thread_is_gc_unsafe_mode (void) { MonoThreadInfo *cur = mono_thread_info_current (); if (!cur) return FALSE; switch (mono_thread_info_current_state (cur)) { case STATE_RUNNING: case STATE_ASYNC_SUSPEND_REQUESTED: return TRUE; default: return FALSE; } } gboolean mono_thread_info_will_not_safepoint (MonoThreadInfo *info) { return info->thread_state.no_safepoints; }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/native/external/zlib-intel/deflate_medium.c
/* * The deflate_medium deflate strategy * * Copyright (C) 2013 Intel Corporation. All rights reserved. * Authors: * Arjan van de Ven <[email protected]> * * For conditions of distribution and use, see copyright notice in zlib.h */ #include "deflate.h" struct match { uInt match_start; uInt match_length; uInt strstart; uInt orgstart; }; static int tr_tally_dist(deflate_state *s, int distance, int length) { return _tr_tally(s, distance, length); } static int tr_tally_lit(deflate_state *s, int c) { return _tr_tally(s, 0, c); } static int emit_match(deflate_state *s, struct match match, IPos hash_head) { int flush = 0; /* matches that are not long enough we need to emit as litterals */ if (match.match_length < MIN_MATCH) { while (match.match_length) { flush += tr_tally_lit (s, s->window[match.strstart]); s->lookahead--; match.strstart++; match.match_length--; } return flush; } check_match(s, match.strstart, match.match_start, match.match_length); flush += tr_tally_dist(s, match.strstart - match.match_start, match.match_length - MIN_MATCH); s->lookahead -= match.match_length; return flush; } static void insert_match(deflate_state *s, struct match match) { IPos hash_head; if (zunlikely(s->lookahead <= match.match_length + MIN_MATCH)) return; /* matches that are not long enough we need to emit as litterals */ if (match.match_length < MIN_MATCH) { while (match.match_length) { match.strstart++; match.match_length--; if (match.match_length) { if (match.strstart >= match.orgstart) { INSERT_STRING(s, match.strstart, hash_head); } } } return; } /* Insert new strings in the hash table only if the match length * is not too large. This saves time but degrades compression. */ if (match.match_length <= 16* s->max_insert_length && s->lookahead >= MIN_MATCH) { match.match_length--; /* string at strstart already in table */ do { match.strstart++; if (zlikely(match.strstart >= match.orgstart)) { INSERT_STRING(s, match.strstart, hash_head); } /* strstart never exceeds WSIZE-MAX_MATCH, so there are * always MIN_MATCH bytes ahead. */ } while (--match.match_length != 0); match.strstart++; } else { match.strstart += match.match_length; match.match_length = 0; s->ins_h = s->window[match.strstart]; if (match.strstart >= 1) { IPos hash_head = 0; INSERT_STRING(s, match.strstart - 1, hash_head); } #if MIN_MATCH != 3 #warning Call UPDATE_HASH() MIN_MATCH-3 more times #endif /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not * matter since it will be recomputed at next deflate call. */ } } static void fizzle_matches(deflate_state *s, struct match *current, struct match *next) { IPos limit; unsigned char *match, *orig; int changed = 0; struct match c,n; uInt maxDist; /* step zero: sanity checks */ if (current->match_length <= 1) return; if (zunlikely(current->match_length > 1 + next->match_start)) return; if (zunlikely(current->match_length > 1 + next->strstart)) return; match = s->window - current->match_length + 1 + next->match_start ; orig = s->window - current->match_length + 1 + next->strstart ; /* quick exit check.. if this fails then don't bother with anything else */ if (zlikely(*match != *orig)) return; /* * check the overlap case and just give up. We can do better in theory, * but unlikely to be worth it */ if (next->match_start + next->match_length >= current->strstart) return; c = *current; n = *next; /* step one: try to move the "next" match to the left as much as possible */ maxDist = MAX_DIST(s); limit = next->strstart > maxDist ? next->strstart - maxDist : 0; match = s->window + n.match_start - 1; orig = s->window + n.strstart - 1; while (*match == *orig) { if (c.match_length < 1) break; if (n.strstart <= limit) break; if (n.match_length >= 256) break; if (n.match_start <= 0) break; n.strstart--; n.match_start--; n.match_length++; c.match_length--; match--; orig--; changed ++; } if (!changed) return; if ( (c.match_length <= 1) && n.match_length != 2) { n.orgstart++; *current = c; *next = n; } else return; } block_state deflate_medium(deflate_state *s, int flush) { struct match current_match, next_match; memset(&current_match, 0, sizeof(struct match)); memset(&next_match, 0, sizeof(struct match)); for (;;) { IPos hash_head = 0; /* head of the hash chain */ int bflush; /* set if current block must be flushed */ /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next current_match. */ if (s->lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { return need_more; } if (s->lookahead == 0) break; /* flush the current block */ next_match.match_length = 0; } s->prev_length = 2; /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ /* If we already have a future match from a previous round, just use that */ if (next_match.match_length > 0) { current_match = next_match; next_match.match_length = 0; } else { hash_head = 0; if (s->lookahead >= MIN_MATCH) { INSERT_STRING(s, s->strstart, hash_head); } if (hash_head && hash_head == s->strstart) hash_head--; /* set up the initial match to be a 1 byte literal */ current_match.match_start = 0; current_match.match_length = 1; current_match.strstart = s->strstart; current_match.orgstart = current_match.strstart; /* Find the longest match, discarding those <= prev_length. * At this point we have always match_length < MIN_MATCH */ if (hash_head != 0 && s->strstart - hash_head <= MAX_DIST(s)) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ current_match.match_length = longest_match (s, hash_head); current_match.match_start = s->match_start; if (current_match.match_length < MIN_MATCH) current_match.match_length = 1; if (current_match.match_start >= current_match.strstart) { /* this can happen due to some restarts */ current_match.match_length = 1; } } } insert_match(s, current_match); /* now, look ahead one */ if (s->lookahead > MIN_LOOKAHEAD) { s->strstart = current_match.strstart + current_match.match_length; INSERT_STRING(s, s->strstart, hash_head); if (hash_head && hash_head == s->strstart) hash_head--; /* set up the initial match to be a 1 byte literal */ next_match.match_start = 0; next_match.match_length = 1; next_match.strstart = s->strstart; next_match.orgstart = next_match.strstart; /* Find the longest match, discarding those <= prev_length. * At this point we have always match_length < MIN_MATCH */ if (hash_head != 0 && s->strstart - hash_head <= MAX_DIST(s)) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ next_match.match_length = longest_match (s, hash_head); next_match.match_start = s->match_start; if (next_match.match_start >= next_match.strstart) /* this can happen due to some restarts */ next_match.match_length = 1; if (next_match.match_length < MIN_MATCH) next_match.match_length = 1; else fizzle_matches(s, &current_match, &next_match); } /* short matches with a very long distance are rarely a good idea encoding wise */ if (next_match.match_length == 3 && (next_match.strstart - next_match.match_start) > 12000) next_match.match_length = 1; s->strstart = current_match.strstart; } else { next_match.match_length = 0; } /* now emit the current match */ bflush = emit_match(s, current_match, hash_head); /* move the "cursor" forward */ s->strstart += current_match.match_length; if (bflush) FLUSH_BLOCK(s, 0); } s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1; if (flush == Z_FINISH) { FLUSH_BLOCK(s, 1); return finish_done; } if (s->last_lit) FLUSH_BLOCK(s, 0); return block_done; }
/* * The deflate_medium deflate strategy * * Copyright (C) 2013 Intel Corporation. All rights reserved. * Authors: * Arjan van de Ven <[email protected]> * * For conditions of distribution and use, see copyright notice in zlib.h */ #include "deflate.h" struct match { uInt match_start; uInt match_length; uInt strstart; uInt orgstart; }; static int tr_tally_dist(deflate_state *s, int distance, int length) { return _tr_tally(s, distance, length); } static int tr_tally_lit(deflate_state *s, int c) { return _tr_tally(s, 0, c); } static int emit_match(deflate_state *s, struct match match, IPos hash_head) { int flush = 0; /* matches that are not long enough we need to emit as litterals */ if (match.match_length < MIN_MATCH) { while (match.match_length) { flush += tr_tally_lit (s, s->window[match.strstart]); s->lookahead--; match.strstart++; match.match_length--; } return flush; } check_match(s, match.strstart, match.match_start, match.match_length); flush += tr_tally_dist(s, match.strstart - match.match_start, match.match_length - MIN_MATCH); s->lookahead -= match.match_length; return flush; } static void insert_match(deflate_state *s, struct match match) { IPos hash_head; if (zunlikely(s->lookahead <= match.match_length + MIN_MATCH)) return; /* matches that are not long enough we need to emit as litterals */ if (match.match_length < MIN_MATCH) { while (match.match_length) { match.strstart++; match.match_length--; if (match.match_length) { if (match.strstart >= match.orgstart) { INSERT_STRING(s, match.strstart, hash_head); } } } return; } /* Insert new strings in the hash table only if the match length * is not too large. This saves time but degrades compression. */ if (match.match_length <= 16* s->max_insert_length && s->lookahead >= MIN_MATCH) { match.match_length--; /* string at strstart already in table */ do { match.strstart++; if (zlikely(match.strstart >= match.orgstart)) { INSERT_STRING(s, match.strstart, hash_head); } /* strstart never exceeds WSIZE-MAX_MATCH, so there are * always MIN_MATCH bytes ahead. */ } while (--match.match_length != 0); match.strstart++; } else { match.strstart += match.match_length; match.match_length = 0; s->ins_h = s->window[match.strstart]; if (match.strstart >= 1) { IPos hash_head = 0; INSERT_STRING(s, match.strstart - 1, hash_head); } #if MIN_MATCH != 3 #warning Call UPDATE_HASH() MIN_MATCH-3 more times #endif /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not * matter since it will be recomputed at next deflate call. */ } } static void fizzle_matches(deflate_state *s, struct match *current, struct match *next) { IPos limit; unsigned char *match, *orig; int changed = 0; struct match c,n; uInt maxDist; /* step zero: sanity checks */ if (current->match_length <= 1) return; if (zunlikely(current->match_length > 1 + next->match_start)) return; if (zunlikely(current->match_length > 1 + next->strstart)) return; match = s->window - current->match_length + 1 + next->match_start ; orig = s->window - current->match_length + 1 + next->strstart ; /* quick exit check.. if this fails then don't bother with anything else */ if (zlikely(*match != *orig)) return; /* * check the overlap case and just give up. We can do better in theory, * but unlikely to be worth it */ if (next->match_start + next->match_length >= current->strstart) return; c = *current; n = *next; /* step one: try to move the "next" match to the left as much as possible */ maxDist = MAX_DIST(s); limit = next->strstart > maxDist ? next->strstart - maxDist : 0; match = s->window + n.match_start - 1; orig = s->window + n.strstart - 1; while (*match == *orig) { if (c.match_length < 1) break; if (n.strstart <= limit) break; if (n.match_length >= 256) break; if (n.match_start <= 0) break; n.strstart--; n.match_start--; n.match_length++; c.match_length--; match--; orig--; changed ++; } if (!changed) return; if ( (c.match_length <= 1) && n.match_length != 2) { n.orgstart++; *current = c; *next = n; } else return; } block_state deflate_medium(deflate_state *s, int flush) { struct match current_match, next_match; memset(&current_match, 0, sizeof(struct match)); memset(&next_match, 0, sizeof(struct match)); for (;;) { IPos hash_head = 0; /* head of the hash chain */ int bflush; /* set if current block must be flushed */ /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next current_match. */ if (s->lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { return need_more; } if (s->lookahead == 0) break; /* flush the current block */ next_match.match_length = 0; } s->prev_length = 2; /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ /* If we already have a future match from a previous round, just use that */ if (next_match.match_length > 0) { current_match = next_match; next_match.match_length = 0; } else { hash_head = 0; if (s->lookahead >= MIN_MATCH) { INSERT_STRING(s, s->strstart, hash_head); } if (hash_head && hash_head == s->strstart) hash_head--; /* set up the initial match to be a 1 byte literal */ current_match.match_start = 0; current_match.match_length = 1; current_match.strstart = s->strstart; current_match.orgstart = current_match.strstart; /* Find the longest match, discarding those <= prev_length. * At this point we have always match_length < MIN_MATCH */ if (hash_head != 0 && s->strstart - hash_head <= MAX_DIST(s)) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ current_match.match_length = longest_match (s, hash_head); current_match.match_start = s->match_start; if (current_match.match_length < MIN_MATCH) current_match.match_length = 1; if (current_match.match_start >= current_match.strstart) { /* this can happen due to some restarts */ current_match.match_length = 1; } } } insert_match(s, current_match); /* now, look ahead one */ if (s->lookahead > MIN_LOOKAHEAD) { s->strstart = current_match.strstart + current_match.match_length; INSERT_STRING(s, s->strstart, hash_head); if (hash_head && hash_head == s->strstart) hash_head--; /* set up the initial match to be a 1 byte literal */ next_match.match_start = 0; next_match.match_length = 1; next_match.strstart = s->strstart; next_match.orgstart = next_match.strstart; /* Find the longest match, discarding those <= prev_length. * At this point we have always match_length < MIN_MATCH */ if (hash_head != 0 && s->strstart - hash_head <= MAX_DIST(s)) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ next_match.match_length = longest_match (s, hash_head); next_match.match_start = s->match_start; if (next_match.match_start >= next_match.strstart) /* this can happen due to some restarts */ next_match.match_length = 1; if (next_match.match_length < MIN_MATCH) next_match.match_length = 1; else fizzle_matches(s, &current_match, &next_match); } /* short matches with a very long distance are rarely a good idea encoding wise */ if (next_match.match_length == 3 && (next_match.strstart - next_match.match_start) > 12000) next_match.match_length = 1; s->strstart = current_match.strstart; } else { next_match.match_length = 0; } /* now emit the current match */ bflush = emit_match(s, current_match, hash_head); /* move the "cursor" forward */ s->strstart += current_match.match_length; if (bflush) FLUSH_BLOCK(s, 0); } s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1; if (flush == Z_FINISH) { FLUSH_BLOCK(s, 1); return finish_done; } if (s->last_lit) FLUSH_BLOCK(s, 0); return block_done; }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/native/public/mono/metadata/metadata.h
/** * \file */ #ifndef __MONO_METADATA_H__ #define __MONO_METADATA_H__ #include <mono/metadata/details/metadata-types.h> MONO_BEGIN_DECLS #define MONO_TYPE_ISSTRUCT(t) mono_type_is_struct (t) #define MONO_TYPE_IS_VOID(t) mono_type_is_void (t) #define MONO_TYPE_IS_POINTER(t) mono_type_is_pointer (t) #define MONO_TYPE_IS_REFERENCE(t) mono_type_is_reference (t) #define MONO_CLASS_IS_INTERFACE(c) ((mono_class_get_flags (c) & TYPE_ATTRIBUTE_INTERFACE) || mono_type_is_generic_parameter (mono_class_get_type (c))) #define MONO_CLASS_IS_IMPORT(c) ((mono_class_get_flags (c) & TYPE_ATTRIBUTE_IMPORT)) /* * This macro is used to extract the size of the table encoded in * the size_bitfield of MonoTableInfo. */ #define mono_metadata_table_size(bitfield,table) ((((bitfield) >> ((table)*2)) & 0x3) + 1) #define mono_metadata_table_count(bitfield) ((bitfield) >> 24) #define MONO_OFFSET_IN_CLAUSE(clause,offset) \ ((clause)->try_offset <= (offset) && (offset) < ((clause)->try_offset + (clause)->try_len)) #define MONO_OFFSET_IN_HANDLER(clause,offset) \ ((clause)->handler_offset <= (offset) && (offset) < ((clause)->handler_offset + (clause)->handler_len)) #define MONO_OFFSET_IN_FILTER(clause,offset) \ ((clause)->flags == MONO_EXCEPTION_CLAUSE_FILTER && (clause)->data.filter_offset <= (offset) && (offset) < ((clause)->handler_offset)) /* * Makes a token based on a table and an index */ #define mono_metadata_make_token(table,idx) (((table) << 24)| (idx)) /* * Returns the table index that this token encodes. */ #define mono_metadata_token_table(token) ((token) >> 24) /* * Returns the index that a token refers to */ #define mono_metadata_token_index(token) ((token) & 0xffffff) #define mono_metadata_token_code(token) ((token) & 0xff000000) #define MONO_API_FUNCTION(ret,name,args) MONO_API ret name args; #include <mono/metadata/details/metadata-functions.h> #undef MONO_API_FUNCTION MONO_END_DECLS #endif /* __MONO_METADATA_H__ */
/** * \file */ #ifndef __MONO_METADATA_H__ #define __MONO_METADATA_H__ #include <mono/metadata/details/metadata-types.h> MONO_BEGIN_DECLS #define MONO_TYPE_ISSTRUCT(t) mono_type_is_struct (t) #define MONO_TYPE_IS_VOID(t) mono_type_is_void (t) #define MONO_TYPE_IS_POINTER(t) mono_type_is_pointer (t) #define MONO_TYPE_IS_REFERENCE(t) mono_type_is_reference (t) #define MONO_CLASS_IS_INTERFACE(c) ((mono_class_get_flags (c) & TYPE_ATTRIBUTE_INTERFACE) || mono_type_is_generic_parameter (mono_class_get_type (c))) #define MONO_CLASS_IS_IMPORT(c) ((mono_class_get_flags (c) & TYPE_ATTRIBUTE_IMPORT)) /* * This macro is used to extract the size of the table encoded in * the size_bitfield of MonoTableInfo. */ #define mono_metadata_table_size(bitfield,table) ((((bitfield) >> ((table)*2)) & 0x3) + 1) #define mono_metadata_table_count(bitfield) ((bitfield) >> 24) #define MONO_OFFSET_IN_CLAUSE(clause,offset) \ ((clause)->try_offset <= (offset) && (offset) < ((clause)->try_offset + (clause)->try_len)) #define MONO_OFFSET_IN_HANDLER(clause,offset) \ ((clause)->handler_offset <= (offset) && (offset) < ((clause)->handler_offset + (clause)->handler_len)) #define MONO_OFFSET_IN_FILTER(clause,offset) \ ((clause)->flags == MONO_EXCEPTION_CLAUSE_FILTER && (clause)->data.filter_offset <= (offset) && (offset) < ((clause)->handler_offset)) /* * Makes a token based on a table and an index */ #define mono_metadata_make_token(table,idx) (((table) << 24)| (idx)) /* * Returns the table index that this token encodes. */ #define mono_metadata_token_table(token) ((token) >> 24) /* * Returns the index that a token refers to */ #define mono_metadata_token_index(token) ((token) & 0xffffff) #define mono_metadata_token_code(token) ((token) & 0xff000000) #define MONO_API_FUNCTION(ret,name,args) MONO_API ret name args; #include <mono/metadata/details/metadata-functions.h> #undef MONO_API_FUNCTION MONO_END_DECLS #endif /* __MONO_METADATA_H__ */
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/native/libs/System.IO.Ports.Native/pal_termios.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "pal_types.h" #include "pal_compiler.h" PALEXPORT int32_t SystemIoPortsNative_TermiosGetSignal(intptr_t fd, int32_t signal); PALEXPORT int32_t SystemIoPortsNative_TermiosSetSignal(intptr_t fd, int32_t signal, int32_t set); PALEXPORT int32_t SystemIoPortsNative_TermiosGetAllSignals(intptr_t fd); PALEXPORT int32_t SystemIoPortsNative_TermiosGetSpeed(intptr_t fd); PALEXPORT int32_t SystemIoPortsNative_TermiosSetSpeed(intptr_t fd, int32_t speed); PALEXPORT int32_t SystemIoPortsNative_TermiosAvailableBytes(intptr_t fd, int32_t readBuffer); PALEXPORT int32_t SystemIoPortsNative_TermiosReset(intptr_t fd, int32_t speed, int32_t dataBits, int32_t stopBits, int32_t parity, int32_t handshake); PALEXPORT int32_t SystemIoPortsNative_TermiosDiscard(intptr_t fd, int32_t queue); PALEXPORT int32_t SystemIoPortsNative_TermiosDrain(intptr_t fd); PALEXPORT int32_t SystemIoPortsNative_TermiosSendBreak(intptr_t fd, int32_t duration);
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "pal_types.h" #include "pal_compiler.h" PALEXPORT int32_t SystemIoPortsNative_TermiosGetSignal(intptr_t fd, int32_t signal); PALEXPORT int32_t SystemIoPortsNative_TermiosSetSignal(intptr_t fd, int32_t signal, int32_t set); PALEXPORT int32_t SystemIoPortsNative_TermiosGetAllSignals(intptr_t fd); PALEXPORT int32_t SystemIoPortsNative_TermiosGetSpeed(intptr_t fd); PALEXPORT int32_t SystemIoPortsNative_TermiosSetSpeed(intptr_t fd, int32_t speed); PALEXPORT int32_t SystemIoPortsNative_TermiosAvailableBytes(intptr_t fd, int32_t readBuffer); PALEXPORT int32_t SystemIoPortsNative_TermiosReset(intptr_t fd, int32_t speed, int32_t dataBits, int32_t stopBits, int32_t parity, int32_t handshake); PALEXPORT int32_t SystemIoPortsNative_TermiosDiscard(intptr_t fd, int32_t queue); PALEXPORT int32_t SystemIoPortsNative_TermiosDrain(intptr_t fd); PALEXPORT int32_t SystemIoPortsNative_TermiosSendBreak(intptr_t fd, int32_t duration);
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/native/libs/System.Security.Cryptography.Native.Android/pal_x509chain.c
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "pal_x509chain.h" #include <pal_x509_types.h> #include <assert.h> #include <stdbool.h> #include <string.h> struct X509ChainContext_t { jobject /*PKIXBuilderParameters*/ params; jobject /*CertPath*/ certPath; jobject /*TrustAnchor*/ trustAnchor; jobject /*ArrayList<Throwable>*/ errorList; jobject /*ArrayList<Throwable>*/ revocationErrorList; }; struct ValidationError_t { uint16_t* message; int index; PAL_X509ChainStatusFlags chainStatus; }; X509ChainContext* AndroidCryptoNative_X509ChainCreateContext(jobject /*X509Certificate*/ cert, jobject* /*X509Certificate[]*/ extraStore, int32_t extraStoreLen) { abort_if_invalid_pointer_argument (cert); if (extraStore == NULL && extraStoreLen != 0) { LOG_WARN ("No extra store pointer provided, but extra store length is %d", extraStoreLen); extraStoreLen = 0; } JNIEnv* env = GetJNIEnv(); X509ChainContext* ret = NULL; INIT_LOCALS(loc, keyStoreType, keyStore, targetSel, params, certList, certStoreType, certStoreParams, certStore); // String keyStoreType = "AndroidCAStore"; // KeyStore keyStore = KeyStore.getInstance(keyStoreType); // keyStore.load(null, null); loc[keyStoreType] = make_java_string(env, "AndroidCAStore"); loc[keyStore] = (*env)->CallStaticObjectMethod(env, g_KeyStoreClass, g_KeyStoreGetInstance, loc[keyStoreType]); ON_EXCEPTION_PRINT_AND_GOTO(cleanup); (*env)->CallVoidMethod(env, loc[keyStore], g_KeyStoreLoad, NULL, NULL); ON_EXCEPTION_PRINT_AND_GOTO(cleanup); // X509CertSelector targetSel = new X509CertSelector(); // targetSel.setCertificate(cert); loc[targetSel] = (*env)->NewObject(env, g_X509CertSelectorClass, g_X509CertSelectorCtor); (*env)->CallVoidMethod(env, loc[targetSel], g_X509CertSelectorSetCertificate, cert); // PKIXBuilderParameters params = new PKIXBuilderParameters(keyStore, targetSelector); loc[params] = (*env)->NewObject( env, g_PKIXBuilderParametersClass, g_PKIXBuilderParametersCtor, loc[keyStore], loc[targetSel]); ON_EXCEPTION_PRINT_AND_GOTO(cleanup); // ArrayList<Certificate> certList = new ArrayList<Certificate>(); // certList.add(cert); // for (int i = 0; i < extraStoreLen; i++) { // certList.add(extraStore[i]); // } loc[certList] = (*env)->NewObject(env, g_ArrayListClass, g_ArrayListCtorWithCapacity, extraStoreLen); (*env)->CallBooleanMethod(env, loc[certList], g_ArrayListAdd, cert); for (int i = 0; i < extraStoreLen; ++i) { (*env)->CallBooleanMethod(env, loc[certList], g_ArrayListAdd, extraStore[i]); } // String certStoreType = "Collection"; // CollectionCertStoreParameters certStoreParams = new CollectionCertStoreParameters(certList); // CertStore certStore = CertStore.getInstance(certStoreType, certStoreParams); loc[certStoreType] = make_java_string(env, "Collection"); loc[certStoreParams] = (*env)->NewObject( env, g_CollectionCertStoreParametersClass, g_CollectionCertStoreParametersCtor, loc[certList]); loc[certStore] = (*env)->CallStaticObjectMethod( env, g_CertStoreClass, g_CertStoreGetInstance, loc[certStoreType], loc[certStoreParams]); ON_EXCEPTION_PRINT_AND_GOTO(cleanup); // params.addCertStore(certStore); (*env)->CallVoidMethod(env, loc[params], g_PKIXBuilderParametersAddCertStore, loc[certStore]); ret = xcalloc(1, sizeof(X509ChainContext)); ret->params = AddGRef(env, loc[params]); ret->errorList = ToGRef(env, (*env)->NewObject(env, g_ArrayListClass, g_ArrayListCtor)); cleanup: RELEASE_LOCALS(loc, env); return ret; } void AndroidCryptoNative_X509ChainDestroyContext(X509ChainContext* ctx) { if (ctx == NULL) return; JNIEnv* env = GetJNIEnv(); ReleaseGRef(env, ctx->params); ReleaseGRef(env, ctx->certPath); ReleaseGRef(env, ctx->trustAnchor); ReleaseGRef(env, ctx->errorList); ReleaseGRef(env, ctx->revocationErrorList); free(ctx); } int32_t AndroidCryptoNative_X509ChainBuild(X509ChainContext* ctx, int64_t timeInMsFromUnixEpoch) { abort_if_invalid_pointer_argument (ctx); JNIEnv* env = GetJNIEnv(); int32_t ret = FAIL; INIT_LOCALS(loc, date, builderType, builder, result, ex, certPath, trustAnchor); jobject params = ctx->params; // Date date = new Date(timeInMsFromUnixEpoch); // params.setDate(date); loc[date] = (*env)->NewObject(env, g_DateClass, g_DateCtor, timeInMsFromUnixEpoch); (*env)->CallVoidMethod(env, params, g_PKIXBuilderParametersSetDate, loc[date]); // Disable revocation checking when building the cert path. It will be handled in a validation pass if the path is // successfully built. // params.setRevocationEnabled(false); (*env)->CallVoidMethod(env, params, g_PKIXBuilderParametersSetRevocationEnabled, false); // String builderType = "PKIX"; // CertPathBuilder builder = CertPathBuilder.getInstance(builderType); // PKIXCertPathBuilderResult result = (PKIXCertPathBuilderResult)builder.build(params); loc[builderType] = make_java_string(env, "PKIX"); loc[builder] = (*env)->CallStaticObjectMethod(env, g_CertPathBuilderClass, g_CertPathBuilderGetInstance, loc[builderType]); loc[result] = (*env)->CallObjectMethod(env, loc[builder], g_CertPathBuilderBuild, params); if (TryGetJNIException(env, &loc[ex], false /*printException*/)) { (*env)->CallBooleanMethod(env, ctx->errorList, g_ArrayListAdd, loc[ex]); goto cleanup; } loc[certPath] = (*env)->CallObjectMethod(env, loc[result], g_PKIXCertPathBuilderResultGetCertPath); loc[trustAnchor] = (*env)->CallObjectMethod(env, loc[result], g_PKIXCertPathBuilderResultGetTrustAnchor); ctx->certPath = AddGRef(env, loc[certPath]); ctx->trustAnchor = AddGRef(env, loc[trustAnchor]); ret = SUCCESS; cleanup: RELEASE_LOCALS(loc, env); return ret; } int32_t AndroidCryptoNative_X509ChainGetCertificateCount(X509ChainContext* ctx) { abort_if_invalid_pointer_argument (ctx); JNIEnv* env = GetJNIEnv(); // List<Certificate> certPathList = certPath.getCertificates(); jobject certPathList = (*env)->CallObjectMethod(env, ctx->certPath, g_CertPathGetCertificates); int certCount = (int)(*env)->CallIntMethod(env, certPathList, g_CollectionSize); (*env)->DeleteLocalRef(env, certPathList); return certCount + 1; // +1 for the trust anchor } int32_t AndroidCryptoNative_X509ChainGetCertificates(X509ChainContext* ctx, jobject* /*X509Certificate[]*/ certs, int32_t certsLen) { abort_if_invalid_pointer_argument (ctx); JNIEnv* env = GetJNIEnv(); int32_t ret = FAIL; // List<Certificate> certPathList = certPath.getCertificates(); jobject certPathList = (*env)->CallObjectMethod(env, ctx->certPath, g_CertPathGetCertificates); int certCount = (int)(*env)->CallIntMethod(env, certPathList, g_CollectionSize); if (certsLen < certCount + 1) goto cleanup; abort_if_invalid_pointer_argument (certs); // for (int i = 0; i < certPathList.size(); ++i) { // Certificate cert = certPathList.get(i); // certs[i] = cert; // } int32_t i; for (i = 0; i < certCount; ++i) { jobject cert = (*env)->CallObjectMethod(env, certPathList, g_ListGet, i); ON_EXCEPTION_PRINT_AND_GOTO(cleanup); certs[i] = ToGRef(env, cert); } // Certificate trustedCert = trustAnchor.getTrustedCert(); // certs[i] = trustedCert; jobject trustedCert = (*env)->CallObjectMethod(env, ctx->trustAnchor, g_TrustAnchorGetTrustedCert); if (i == 0 || !(*env)->IsSameObject(env, certs[i-1], trustedCert)) { certs[i] = ToGRef(env, trustedCert); ret = i + 1; } else { ret = i; certs[i] = NULL; } cleanup: (*env)->DeleteLocalRef(env, certPathList); return ret; } int32_t AndroidCryptoNative_X509ChainGetErrorCount(X509ChainContext* ctx) { abort_if_invalid_pointer_argument(ctx); abort_unless(ctx->errorList != NULL, "errorList is NULL in X509ChainContext"); JNIEnv* env = GetJNIEnv(); int32_t count = (*env)->CallIntMethod(env, ctx->errorList, g_CollectionSize); if (ctx->revocationErrorList != NULL) { count += (*env)->CallIntMethod(env, ctx->revocationErrorList, g_CollectionSize); } return count; } enum { PKIXREASON_NAME_CHAINING, PKIXREASON_INVALID_KEY_USAGE, PKIXREASON_INVALID_POLICY, PKIXREASON_NO_TRUST_ANCHOR, PKIXREASON_UNRECOGNIZED_CRIT_EXT, PKIXREASON_NOT_CA_CERT, PKIXREASON_PATH_TOO_LONG, PKIXREASON_INVALID_NAME, }; enum { BASICREASON_UNSPECIFIED, BASICREASON_EXPIRED, BASICREASON_NOT_YET_VALID, BASICREASON_REVOKED, BASICREASON_UNDETERMINED_REVOCATION_STATUS, BASICREASON_INVALID_SIGNATURE, BASICREASON_ALGORITHM_CONSTRAINED, }; static PAL_X509ChainStatusFlags ChainStatusFromValidatorExceptionReason(JNIEnv* env, jobject reason) { int value = (*env)->CallIntMethod(env, reason, g_EnumOrdinal); if (g_CertPathExceptionBasicReasonClass != NULL && (*env)->IsInstanceOf(env, reason, g_CertPathExceptionBasicReasonClass)) { switch (value) { case BASICREASON_UNSPECIFIED: return PAL_X509ChainPartialChain; case BASICREASON_EXPIRED: case BASICREASON_NOT_YET_VALID: return PAL_X509ChainNotTimeValid; case BASICREASON_REVOKED: return PAL_X509ChainRevoked; case BASICREASON_UNDETERMINED_REVOCATION_STATUS: return PAL_X509ChainRevocationStatusUnknown; case BASICREASON_INVALID_SIGNATURE: return PAL_X509ChainNotSignatureValid; case BASICREASON_ALGORITHM_CONSTRAINED: return PAL_X509ChainPartialChain; } } else if (g_PKIXReasonClass != NULL && (*env)->IsInstanceOf(env, reason, g_PKIXReasonClass)) { switch (value) { case PKIXREASON_NAME_CHAINING: return PAL_X509ChainPartialChain; case PKIXREASON_INVALID_KEY_USAGE: return PAL_X509ChainNotValidForUsage; case PKIXREASON_INVALID_POLICY: return PAL_X509ChainInvalidPolicyConstraints; case PKIXREASON_NO_TRUST_ANCHOR: return PAL_X509ChainPartialChain; case PKIXREASON_UNRECOGNIZED_CRIT_EXT: return PAL_X509ChainHasNotSupportedCriticalExtension; case PKIXREASON_NOT_CA_CERT: return PAL_X509ChainUntrustedRoot; case PKIXREASON_PATH_TOO_LONG: return PAL_X509ChainInvalidBasicConstraints; case PKIXREASON_INVALID_NAME: return PAL_X509ChainInvalidNameConstraints; } } return PAL_X509ChainPartialChain; } static void PopulateValidationError(JNIEnv* env, jobject error, bool isRevocationError, ValidationError* out) { int index = -1; PAL_X509ChainStatusFlags chainStatus = PAL_X509ChainNoError; if ((*env)->IsInstanceOf(env, error, g_CertPathValidatorExceptionClass)) { index = (*env)->CallIntMethod(env, error, g_CertPathValidatorExceptionGetIndex); // Get the reason (if the API is available) and convert it to a chain status flag if (g_CertPathValidatorExceptionGetReason != NULL) { jobject reason = (*env)->CallObjectMethod(env, error, g_CertPathValidatorExceptionGetReason); chainStatus = ChainStatusFromValidatorExceptionReason(env, reason); (*env)->DeleteLocalRef(env, reason); } } else { chainStatus = isRevocationError ? PAL_X509ChainRevocationStatusUnknown : PAL_X509ChainPartialChain; } jobject message = (*env)->CallObjectMethod(env, error, g_ThrowableGetMessage); uint16_t* messagePtr = NULL; if (message != NULL) { jsize messageLen = message == NULL ? 0 : (*env)->GetStringLength(env, message); // +1 for null terminator messagePtr = xmalloc(sizeof(uint16_t) * (size_t)(messageLen + 1)); messagePtr[messageLen] = '\0'; (*env)->GetStringRegion(env, message, 0, messageLen, (jchar*)messagePtr); } // If the error is known to be from revocation checking, but couldn't be mapped to a revocation status, // report it as RevocationStatusUnknown if (isRevocationError && chainStatus != PAL_X509ChainRevocationStatusUnknown && chainStatus != PAL_X509ChainRevoked) { chainStatus = PAL_X509ChainRevocationStatusUnknown; } out->message = messagePtr; out->index = index; out->chainStatus = chainStatus; (*env)->DeleteLocalRef(env, message); } int32_t AndroidCryptoNative_X509ChainGetErrors(X509ChainContext* ctx, ValidationError* errors, int32_t errorsLen) { abort_if_invalid_pointer_argument (ctx); abort_unless(ctx->errorList != NULL, "errorList is NULL in X509ChainContext"); JNIEnv* env = GetJNIEnv(); int32_t ret = FAIL; int32_t errorCount = (*env)->CallIntMethod(env, ctx->errorList, g_CollectionSize); int32_t revocationErrorCount = ctx->revocationErrorList == NULL ? 0 : (*env)->CallIntMethod(env, ctx->revocationErrorList, g_CollectionSize); if (errorsLen < errorCount + revocationErrorCount) goto exit; abort_if_invalid_pointer_argument (errors); // for (int i = 0; i < errorList.size(); ++i) { // Throwable error = errorList.get(i); // << populate errors[i] >> // } for (int32_t i = 0; i < errorCount; ++i) { jobject error = (*env)->CallObjectMethod(env, ctx->errorList, g_ListGet, i); ON_EXCEPTION_PRINT_AND_GOTO(exit); PopulateValidationError(env, error, false /*isRevocationError*/, &errors[i]); (*env)->DeleteLocalRef(env, error); } // for (int i = 0; i < revocationErrorList.size(); ++i) { // Throwable error = revocationErrorList.get(i); // << populate errors[i] >> // } if(ctx->revocationErrorList != NULL) { // double check, don't just trust the count to protect us from a segfault for (int32_t i = 0; i < revocationErrorCount; ++i) { jobject error = (*env)->CallObjectMethod(env, ctx->revocationErrorList, g_ListGet, i); ON_EXCEPTION_PRINT_AND_GOTO(exit); PopulateValidationError(env, error, true /*isRevocationError*/, &errors[errorCount + i]); (*env)->DeleteLocalRef(env, error); } } ret = SUCCESS; exit: return ret; } int32_t AndroidCryptoNative_X509ChainSetCustomTrustStore(X509ChainContext* ctx, jobject* /*X509Certificate*/ customTrustStore, int32_t customTrustStoreLen) { abort_if_invalid_pointer_argument (ctx); if (customTrustStoreLen > 0) { abort_if_invalid_pointer_argument (customTrustStore); } JNIEnv* env = GetJNIEnv(); // HashSet<TrustAnchor> anchors = new HashSet<TrustAnchor>(customTrustStoreLen); // for (Certificate cert : customTrustStore) { // TrustAnchor anchor = new TrustAnchor(cert, null); // anchors.Add(anchor); // } jobject anchors = (*env)->NewObject(env, g_HashSetClass, g_HashSetCtorWithCapacity, customTrustStoreLen); for (int i = 0; i < customTrustStoreLen; ++i) { jobject anchor = (*env)->NewObject(env, g_TrustAnchorClass, g_TrustAnchorCtor, customTrustStore[i], NULL); (*env)->CallBooleanMethod(env, anchors, g_HashSetAdd, anchor); (*env)->DeleteLocalRef(env, anchor); } // params.setTrustAnchors(anchors); (*env)->CallVoidMethod(env, ctx->params, g_PKIXBuilderParametersSetTrustAnchors, anchors); (*env)->DeleteLocalRef(env, anchors); return CheckJNIExceptions(env) ? FAIL : SUCCESS; } bool AndroidCryptoNative_X509ChainSupportsRevocationOptions(void) { return g_CertPathValidatorGetRevocationChecker != NULL && g_PKIXRevocationCheckerClass != NULL; } static jobject /*CertPath*/ CreateCertPathFromAnchor(JNIEnv* env, jobject /*TrustAnchor*/ trustAnchor) { jobject ret = NULL; INIT_LOCALS(loc, certList, trustedCert, certFactoryType, certFactory); // ArrayList<Certificate> certList = new ArrayList<Certificate>(1); loc[certList] = (*env)->NewObject(env, g_ArrayListClass, g_ArrayListCtorWithCapacity, 1); // Certificate trustedCert = trustAnchor.getTrustedCert(); // certList.add(trustedCert); loc[trustedCert] = (*env)->CallObjectMethod(env, trustAnchor, g_TrustAnchorGetTrustedCert); (*env)->CallBooleanMethod(env, loc[certList], g_ArrayListAdd, loc[trustedCert]); // CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); loc[certFactoryType] = make_java_string(env, "X.509"); loc[certFactory] = (*env)->CallStaticObjectMethod(env, g_CertFactoryClass, g_CertFactoryGetInstance, loc[certFactoryType]); ON_EXCEPTION_PRINT_AND_GOTO(cleanup); // CertPath certPath = certFactory.generateCertPath(certList); jobject certPath = (*env)->CallObjectMethod(env, loc[certFactory], g_CertFactoryGenerateCertPathFromList, loc[certList]); ON_EXCEPTION_PRINT_AND_GOTO(cleanup); ret = certPath; cleanup: RELEASE_LOCALS(loc, env); return ret; } static int32_t ValidateWithRevocation(JNIEnv* env, X509ChainContext* ctx, jobject /*CertPathValidator*/ validator, PAL_X509RevocationMode revocationMode, PAL_X509RevocationFlag revocationFlag) { abort_if_invalid_pointer_argument (ctx); abort_if_invalid_pointer_argument (validator); int32_t ret = FAIL; INIT_LOCALS(loc, certPathFromAnchor, options, checker, result, ex); if (revocationMode == X509RevocationMode_Offline) { // Android does not supply a way to disable OCSP/CRL fetching LOG_INFO("Treating revocation mode 'Offline' as 'Online'."); } jobject certPathToUse = NULL; if (revocationFlag == X509RevocationFlag_EntireChain) { LOG_INFO("Treating revocation flag 'EntireChain' as 'ExcludeRoot'. " "Revocation will be not be checked for root certificate."); certPathToUse = ctx->certPath; } else if (revocationFlag == X509RevocationFlag_EndCertificateOnly) { // List<Certificate> certPathList = certPath.getCertificates(); // int certCount = certPathList.size(); jobject certPathList = (*env)->CallObjectMethod(env, ctx->certPath, g_CertPathGetCertificates); int certCount = (int)(*env)->CallIntMethod(env, certPathList, g_CollectionSize); if (certCount == 0) { // If the chain only consists only of the trust anchor, create a path with just // the trust anchor for revocation checking for end certificate only. This should // still pass normal (non-revocation) validation when it is the only certificate. loc[certPathFromAnchor] = CreateCertPathFromAnchor(env, ctx->trustAnchor); certPathToUse = loc[certPathFromAnchor]; } else { certPathToUse = ctx->certPath; if (AndroidCryptoNative_X509ChainSupportsRevocationOptions()) { // Only add the ONLY_END_ENTITY if we are not just checking the trust anchor. If ONLY_END_ENTITY is // specified, revocation checking will skip the trust anchor even if it is the only certificate. // HashSet<PKIXRevocationChecker.Option> options = new HashSet<PKIXRevocationChecker.Option>(3); // options.add(PKIXRevocationChecker.Option.ONLY_END_ENTITY); loc[options] = (*env)->NewObject(env, g_HashSetClass, g_HashSetCtorWithCapacity, 3); jobject endOnly = (*env)->GetStaticObjectField( env, g_PKIXRevocationCheckerOptionClass, g_PKIXRevocationCheckerOptionOnlyEndEntity); (*env)->CallBooleanMethod(env, loc[options], g_HashSetAdd, endOnly); (*env)->DeleteLocalRef(env, endOnly); } else { LOG_INFO("Treating revocation flag 'EndCertificateOnly' as 'ExcludeRoot'. " "Revocation will be checked for non-end certificates."); } } (*env)->DeleteLocalRef(env, certPathList); } else { abort_unless(revocationFlag == X509RevocationFlag_ExcludeRoot, "revocationFlag must be X509RevocationFlag_ExcludeRoot"); certPathToUse = ctx->certPath; } jobject params = ctx->params; if (AndroidCryptoNative_X509ChainSupportsRevocationOptions()) { // PKIXRevocationChecker checker = validator.getRevocationChecker(); loc[checker] = (*env)->CallObjectMethod(env, validator, g_CertPathValidatorGetRevocationChecker); ON_EXCEPTION_PRINT_AND_GOTO(cleanup); // Set any specific options if (loc[options] != NULL) { // checker.setOptions(options); (*env)->CallVoidMethod(env, loc[checker], g_PKIXRevocationCheckerSetOptions, loc[options]); } // params.addCertPathChecker(checker); (*env)->CallVoidMethod(env, params, g_PKIXBuilderParametersAddCertPathChecker, loc[checker]); } // params.setRevocationEnabled(true); // PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult)validator.validate(certPathToUse, params); (*env)->CallVoidMethod(env, params, g_PKIXBuilderParametersSetRevocationEnabled, true); loc[result] = (*env)->CallObjectMethod(env, validator, g_CertPathValidatorValidate, certPathToUse, params); if (TryGetJNIException(env, &loc[ex], false /*printException*/)) { if (ctx->revocationErrorList == NULL) { ctx->revocationErrorList = ToGRef(env, (*env)->NewObject(env, g_ArrayListClass, g_ArrayListCtor)); } (*env)->CallBooleanMethod(env, ctx->revocationErrorList, g_ArrayListAdd, loc[ex]); } ret = SUCCESS; cleanup: RELEASE_LOCALS(loc, env); return ret; } int32_t AndroidCryptoNative_X509ChainValidate(X509ChainContext* ctx, PAL_X509RevocationMode revocationMode, PAL_X509RevocationFlag revocationFlag, bool* checkedRevocation) { abort_if_invalid_pointer_argument (ctx); abort_if_invalid_pointer_argument (checkedRevocation); JNIEnv* env = GetJNIEnv(); *checkedRevocation = false; int32_t ret = FAIL; INIT_LOCALS(loc, validatorType, validator, result, ex); // String validatorType = "PKIX"; // CertPathValidator validator = CertPathValidator.getInstance(validatorType); loc[validatorType] = make_java_string(env, "PKIX"); loc[validator] = (*env)->CallStaticObjectMethod( env, g_CertPathValidatorClass, g_CertPathValidatorGetInstance, loc[validatorType]); ON_EXCEPTION_PRINT_AND_GOTO(cleanup); // PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult)validator.validate(certPath, params); loc[result] = (*env)->CallObjectMethod(env, loc[validator], g_CertPathValidatorValidate, ctx->certPath, ctx->params); if (TryGetJNIException(env, &loc[ex], false /*printException*/)) { (*env)->CallBooleanMethod(env, ctx->errorList, g_ArrayListAdd, loc[ex]); ret = SUCCESS; } else if (revocationMode != X509RevocationMode_NoCheck) { ret = ValidateWithRevocation(env, ctx, loc[validator], revocationMode, revocationFlag); *checkedRevocation = true; } else { ret = SUCCESS; } cleanup: RELEASE_LOCALS(loc, env); return ret; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "pal_x509chain.h" #include <pal_x509_types.h> #include <assert.h> #include <stdbool.h> #include <string.h> struct X509ChainContext_t { jobject /*PKIXBuilderParameters*/ params; jobject /*CertPath*/ certPath; jobject /*TrustAnchor*/ trustAnchor; jobject /*ArrayList<Throwable>*/ errorList; jobject /*ArrayList<Throwable>*/ revocationErrorList; }; struct ValidationError_t { uint16_t* message; int index; PAL_X509ChainStatusFlags chainStatus; }; X509ChainContext* AndroidCryptoNative_X509ChainCreateContext(jobject /*X509Certificate*/ cert, jobject* /*X509Certificate[]*/ extraStore, int32_t extraStoreLen) { abort_if_invalid_pointer_argument (cert); if (extraStore == NULL && extraStoreLen != 0) { LOG_WARN ("No extra store pointer provided, but extra store length is %d", extraStoreLen); extraStoreLen = 0; } JNIEnv* env = GetJNIEnv(); X509ChainContext* ret = NULL; INIT_LOCALS(loc, keyStoreType, keyStore, targetSel, params, certList, certStoreType, certStoreParams, certStore); // String keyStoreType = "AndroidCAStore"; // KeyStore keyStore = KeyStore.getInstance(keyStoreType); // keyStore.load(null, null); loc[keyStoreType] = make_java_string(env, "AndroidCAStore"); loc[keyStore] = (*env)->CallStaticObjectMethod(env, g_KeyStoreClass, g_KeyStoreGetInstance, loc[keyStoreType]); ON_EXCEPTION_PRINT_AND_GOTO(cleanup); (*env)->CallVoidMethod(env, loc[keyStore], g_KeyStoreLoad, NULL, NULL); ON_EXCEPTION_PRINT_AND_GOTO(cleanup); // X509CertSelector targetSel = new X509CertSelector(); // targetSel.setCertificate(cert); loc[targetSel] = (*env)->NewObject(env, g_X509CertSelectorClass, g_X509CertSelectorCtor); (*env)->CallVoidMethod(env, loc[targetSel], g_X509CertSelectorSetCertificate, cert); // PKIXBuilderParameters params = new PKIXBuilderParameters(keyStore, targetSelector); loc[params] = (*env)->NewObject( env, g_PKIXBuilderParametersClass, g_PKIXBuilderParametersCtor, loc[keyStore], loc[targetSel]); ON_EXCEPTION_PRINT_AND_GOTO(cleanup); // ArrayList<Certificate> certList = new ArrayList<Certificate>(); // certList.add(cert); // for (int i = 0; i < extraStoreLen; i++) { // certList.add(extraStore[i]); // } loc[certList] = (*env)->NewObject(env, g_ArrayListClass, g_ArrayListCtorWithCapacity, extraStoreLen); (*env)->CallBooleanMethod(env, loc[certList], g_ArrayListAdd, cert); for (int i = 0; i < extraStoreLen; ++i) { (*env)->CallBooleanMethod(env, loc[certList], g_ArrayListAdd, extraStore[i]); } // String certStoreType = "Collection"; // CollectionCertStoreParameters certStoreParams = new CollectionCertStoreParameters(certList); // CertStore certStore = CertStore.getInstance(certStoreType, certStoreParams); loc[certStoreType] = make_java_string(env, "Collection"); loc[certStoreParams] = (*env)->NewObject( env, g_CollectionCertStoreParametersClass, g_CollectionCertStoreParametersCtor, loc[certList]); loc[certStore] = (*env)->CallStaticObjectMethod( env, g_CertStoreClass, g_CertStoreGetInstance, loc[certStoreType], loc[certStoreParams]); ON_EXCEPTION_PRINT_AND_GOTO(cleanup); // params.addCertStore(certStore); (*env)->CallVoidMethod(env, loc[params], g_PKIXBuilderParametersAddCertStore, loc[certStore]); ret = xcalloc(1, sizeof(X509ChainContext)); ret->params = AddGRef(env, loc[params]); ret->errorList = ToGRef(env, (*env)->NewObject(env, g_ArrayListClass, g_ArrayListCtor)); cleanup: RELEASE_LOCALS(loc, env); return ret; } void AndroidCryptoNative_X509ChainDestroyContext(X509ChainContext* ctx) { if (ctx == NULL) return; JNIEnv* env = GetJNIEnv(); ReleaseGRef(env, ctx->params); ReleaseGRef(env, ctx->certPath); ReleaseGRef(env, ctx->trustAnchor); ReleaseGRef(env, ctx->errorList); ReleaseGRef(env, ctx->revocationErrorList); free(ctx); } int32_t AndroidCryptoNative_X509ChainBuild(X509ChainContext* ctx, int64_t timeInMsFromUnixEpoch) { abort_if_invalid_pointer_argument (ctx); JNIEnv* env = GetJNIEnv(); int32_t ret = FAIL; INIT_LOCALS(loc, date, builderType, builder, result, ex, certPath, trustAnchor); jobject params = ctx->params; // Date date = new Date(timeInMsFromUnixEpoch); // params.setDate(date); loc[date] = (*env)->NewObject(env, g_DateClass, g_DateCtor, timeInMsFromUnixEpoch); (*env)->CallVoidMethod(env, params, g_PKIXBuilderParametersSetDate, loc[date]); // Disable revocation checking when building the cert path. It will be handled in a validation pass if the path is // successfully built. // params.setRevocationEnabled(false); (*env)->CallVoidMethod(env, params, g_PKIXBuilderParametersSetRevocationEnabled, false); // String builderType = "PKIX"; // CertPathBuilder builder = CertPathBuilder.getInstance(builderType); // PKIXCertPathBuilderResult result = (PKIXCertPathBuilderResult)builder.build(params); loc[builderType] = make_java_string(env, "PKIX"); loc[builder] = (*env)->CallStaticObjectMethod(env, g_CertPathBuilderClass, g_CertPathBuilderGetInstance, loc[builderType]); loc[result] = (*env)->CallObjectMethod(env, loc[builder], g_CertPathBuilderBuild, params); if (TryGetJNIException(env, &loc[ex], false /*printException*/)) { (*env)->CallBooleanMethod(env, ctx->errorList, g_ArrayListAdd, loc[ex]); goto cleanup; } loc[certPath] = (*env)->CallObjectMethod(env, loc[result], g_PKIXCertPathBuilderResultGetCertPath); loc[trustAnchor] = (*env)->CallObjectMethod(env, loc[result], g_PKIXCertPathBuilderResultGetTrustAnchor); ctx->certPath = AddGRef(env, loc[certPath]); ctx->trustAnchor = AddGRef(env, loc[trustAnchor]); ret = SUCCESS; cleanup: RELEASE_LOCALS(loc, env); return ret; } int32_t AndroidCryptoNative_X509ChainGetCertificateCount(X509ChainContext* ctx) { abort_if_invalid_pointer_argument (ctx); JNIEnv* env = GetJNIEnv(); // List<Certificate> certPathList = certPath.getCertificates(); jobject certPathList = (*env)->CallObjectMethod(env, ctx->certPath, g_CertPathGetCertificates); int certCount = (int)(*env)->CallIntMethod(env, certPathList, g_CollectionSize); (*env)->DeleteLocalRef(env, certPathList); return certCount + 1; // +1 for the trust anchor } int32_t AndroidCryptoNative_X509ChainGetCertificates(X509ChainContext* ctx, jobject* /*X509Certificate[]*/ certs, int32_t certsLen) { abort_if_invalid_pointer_argument (ctx); JNIEnv* env = GetJNIEnv(); int32_t ret = FAIL; // List<Certificate> certPathList = certPath.getCertificates(); jobject certPathList = (*env)->CallObjectMethod(env, ctx->certPath, g_CertPathGetCertificates); int certCount = (int)(*env)->CallIntMethod(env, certPathList, g_CollectionSize); if (certsLen < certCount + 1) goto cleanup; abort_if_invalid_pointer_argument (certs); // for (int i = 0; i < certPathList.size(); ++i) { // Certificate cert = certPathList.get(i); // certs[i] = cert; // } int32_t i; for (i = 0; i < certCount; ++i) { jobject cert = (*env)->CallObjectMethod(env, certPathList, g_ListGet, i); ON_EXCEPTION_PRINT_AND_GOTO(cleanup); certs[i] = ToGRef(env, cert); } // Certificate trustedCert = trustAnchor.getTrustedCert(); // certs[i] = trustedCert; jobject trustedCert = (*env)->CallObjectMethod(env, ctx->trustAnchor, g_TrustAnchorGetTrustedCert); if (i == 0 || !(*env)->IsSameObject(env, certs[i-1], trustedCert)) { certs[i] = ToGRef(env, trustedCert); ret = i + 1; } else { ret = i; certs[i] = NULL; } cleanup: (*env)->DeleteLocalRef(env, certPathList); return ret; } int32_t AndroidCryptoNative_X509ChainGetErrorCount(X509ChainContext* ctx) { abort_if_invalid_pointer_argument(ctx); abort_unless(ctx->errorList != NULL, "errorList is NULL in X509ChainContext"); JNIEnv* env = GetJNIEnv(); int32_t count = (*env)->CallIntMethod(env, ctx->errorList, g_CollectionSize); if (ctx->revocationErrorList != NULL) { count += (*env)->CallIntMethod(env, ctx->revocationErrorList, g_CollectionSize); } return count; } enum { PKIXREASON_NAME_CHAINING, PKIXREASON_INVALID_KEY_USAGE, PKIXREASON_INVALID_POLICY, PKIXREASON_NO_TRUST_ANCHOR, PKIXREASON_UNRECOGNIZED_CRIT_EXT, PKIXREASON_NOT_CA_CERT, PKIXREASON_PATH_TOO_LONG, PKIXREASON_INVALID_NAME, }; enum { BASICREASON_UNSPECIFIED, BASICREASON_EXPIRED, BASICREASON_NOT_YET_VALID, BASICREASON_REVOKED, BASICREASON_UNDETERMINED_REVOCATION_STATUS, BASICREASON_INVALID_SIGNATURE, BASICREASON_ALGORITHM_CONSTRAINED, }; static PAL_X509ChainStatusFlags ChainStatusFromValidatorExceptionReason(JNIEnv* env, jobject reason) { int value = (*env)->CallIntMethod(env, reason, g_EnumOrdinal); if (g_CertPathExceptionBasicReasonClass != NULL && (*env)->IsInstanceOf(env, reason, g_CertPathExceptionBasicReasonClass)) { switch (value) { case BASICREASON_UNSPECIFIED: return PAL_X509ChainPartialChain; case BASICREASON_EXPIRED: case BASICREASON_NOT_YET_VALID: return PAL_X509ChainNotTimeValid; case BASICREASON_REVOKED: return PAL_X509ChainRevoked; case BASICREASON_UNDETERMINED_REVOCATION_STATUS: return PAL_X509ChainRevocationStatusUnknown; case BASICREASON_INVALID_SIGNATURE: return PAL_X509ChainNotSignatureValid; case BASICREASON_ALGORITHM_CONSTRAINED: return PAL_X509ChainPartialChain; } } else if (g_PKIXReasonClass != NULL && (*env)->IsInstanceOf(env, reason, g_PKIXReasonClass)) { switch (value) { case PKIXREASON_NAME_CHAINING: return PAL_X509ChainPartialChain; case PKIXREASON_INVALID_KEY_USAGE: return PAL_X509ChainNotValidForUsage; case PKIXREASON_INVALID_POLICY: return PAL_X509ChainInvalidPolicyConstraints; case PKIXREASON_NO_TRUST_ANCHOR: return PAL_X509ChainPartialChain; case PKIXREASON_UNRECOGNIZED_CRIT_EXT: return PAL_X509ChainHasNotSupportedCriticalExtension; case PKIXREASON_NOT_CA_CERT: return PAL_X509ChainUntrustedRoot; case PKIXREASON_PATH_TOO_LONG: return PAL_X509ChainInvalidBasicConstraints; case PKIXREASON_INVALID_NAME: return PAL_X509ChainInvalidNameConstraints; } } return PAL_X509ChainPartialChain; } static void PopulateValidationError(JNIEnv* env, jobject error, bool isRevocationError, ValidationError* out) { int index = -1; PAL_X509ChainStatusFlags chainStatus = PAL_X509ChainNoError; if ((*env)->IsInstanceOf(env, error, g_CertPathValidatorExceptionClass)) { index = (*env)->CallIntMethod(env, error, g_CertPathValidatorExceptionGetIndex); // Get the reason (if the API is available) and convert it to a chain status flag if (g_CertPathValidatorExceptionGetReason != NULL) { jobject reason = (*env)->CallObjectMethod(env, error, g_CertPathValidatorExceptionGetReason); chainStatus = ChainStatusFromValidatorExceptionReason(env, reason); (*env)->DeleteLocalRef(env, reason); } } else { chainStatus = isRevocationError ? PAL_X509ChainRevocationStatusUnknown : PAL_X509ChainPartialChain; } jobject message = (*env)->CallObjectMethod(env, error, g_ThrowableGetMessage); uint16_t* messagePtr = NULL; if (message != NULL) { jsize messageLen = message == NULL ? 0 : (*env)->GetStringLength(env, message); // +1 for null terminator messagePtr = xmalloc(sizeof(uint16_t) * (size_t)(messageLen + 1)); messagePtr[messageLen] = '\0'; (*env)->GetStringRegion(env, message, 0, messageLen, (jchar*)messagePtr); } // If the error is known to be from revocation checking, but couldn't be mapped to a revocation status, // report it as RevocationStatusUnknown if (isRevocationError && chainStatus != PAL_X509ChainRevocationStatusUnknown && chainStatus != PAL_X509ChainRevoked) { chainStatus = PAL_X509ChainRevocationStatusUnknown; } out->message = messagePtr; out->index = index; out->chainStatus = chainStatus; (*env)->DeleteLocalRef(env, message); } int32_t AndroidCryptoNative_X509ChainGetErrors(X509ChainContext* ctx, ValidationError* errors, int32_t errorsLen) { abort_if_invalid_pointer_argument (ctx); abort_unless(ctx->errorList != NULL, "errorList is NULL in X509ChainContext"); JNIEnv* env = GetJNIEnv(); int32_t ret = FAIL; int32_t errorCount = (*env)->CallIntMethod(env, ctx->errorList, g_CollectionSize); int32_t revocationErrorCount = ctx->revocationErrorList == NULL ? 0 : (*env)->CallIntMethod(env, ctx->revocationErrorList, g_CollectionSize); if (errorsLen < errorCount + revocationErrorCount) goto exit; abort_if_invalid_pointer_argument (errors); // for (int i = 0; i < errorList.size(); ++i) { // Throwable error = errorList.get(i); // << populate errors[i] >> // } for (int32_t i = 0; i < errorCount; ++i) { jobject error = (*env)->CallObjectMethod(env, ctx->errorList, g_ListGet, i); ON_EXCEPTION_PRINT_AND_GOTO(exit); PopulateValidationError(env, error, false /*isRevocationError*/, &errors[i]); (*env)->DeleteLocalRef(env, error); } // for (int i = 0; i < revocationErrorList.size(); ++i) { // Throwable error = revocationErrorList.get(i); // << populate errors[i] >> // } if(ctx->revocationErrorList != NULL) { // double check, don't just trust the count to protect us from a segfault for (int32_t i = 0; i < revocationErrorCount; ++i) { jobject error = (*env)->CallObjectMethod(env, ctx->revocationErrorList, g_ListGet, i); ON_EXCEPTION_PRINT_AND_GOTO(exit); PopulateValidationError(env, error, true /*isRevocationError*/, &errors[errorCount + i]); (*env)->DeleteLocalRef(env, error); } } ret = SUCCESS; exit: return ret; } int32_t AndroidCryptoNative_X509ChainSetCustomTrustStore(X509ChainContext* ctx, jobject* /*X509Certificate*/ customTrustStore, int32_t customTrustStoreLen) { abort_if_invalid_pointer_argument (ctx); if (customTrustStoreLen > 0) { abort_if_invalid_pointer_argument (customTrustStore); } JNIEnv* env = GetJNIEnv(); // HashSet<TrustAnchor> anchors = new HashSet<TrustAnchor>(customTrustStoreLen); // for (Certificate cert : customTrustStore) { // TrustAnchor anchor = new TrustAnchor(cert, null); // anchors.Add(anchor); // } jobject anchors = (*env)->NewObject(env, g_HashSetClass, g_HashSetCtorWithCapacity, customTrustStoreLen); for (int i = 0; i < customTrustStoreLen; ++i) { jobject anchor = (*env)->NewObject(env, g_TrustAnchorClass, g_TrustAnchorCtor, customTrustStore[i], NULL); (*env)->CallBooleanMethod(env, anchors, g_HashSetAdd, anchor); (*env)->DeleteLocalRef(env, anchor); } // params.setTrustAnchors(anchors); (*env)->CallVoidMethod(env, ctx->params, g_PKIXBuilderParametersSetTrustAnchors, anchors); (*env)->DeleteLocalRef(env, anchors); return CheckJNIExceptions(env) ? FAIL : SUCCESS; } bool AndroidCryptoNative_X509ChainSupportsRevocationOptions(void) { return g_CertPathValidatorGetRevocationChecker != NULL && g_PKIXRevocationCheckerClass != NULL; } static jobject /*CertPath*/ CreateCertPathFromAnchor(JNIEnv* env, jobject /*TrustAnchor*/ trustAnchor) { jobject ret = NULL; INIT_LOCALS(loc, certList, trustedCert, certFactoryType, certFactory); // ArrayList<Certificate> certList = new ArrayList<Certificate>(1); loc[certList] = (*env)->NewObject(env, g_ArrayListClass, g_ArrayListCtorWithCapacity, 1); // Certificate trustedCert = trustAnchor.getTrustedCert(); // certList.add(trustedCert); loc[trustedCert] = (*env)->CallObjectMethod(env, trustAnchor, g_TrustAnchorGetTrustedCert); (*env)->CallBooleanMethod(env, loc[certList], g_ArrayListAdd, loc[trustedCert]); // CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); loc[certFactoryType] = make_java_string(env, "X.509"); loc[certFactory] = (*env)->CallStaticObjectMethod(env, g_CertFactoryClass, g_CertFactoryGetInstance, loc[certFactoryType]); ON_EXCEPTION_PRINT_AND_GOTO(cleanup); // CertPath certPath = certFactory.generateCertPath(certList); jobject certPath = (*env)->CallObjectMethod(env, loc[certFactory], g_CertFactoryGenerateCertPathFromList, loc[certList]); ON_EXCEPTION_PRINT_AND_GOTO(cleanup); ret = certPath; cleanup: RELEASE_LOCALS(loc, env); return ret; } static int32_t ValidateWithRevocation(JNIEnv* env, X509ChainContext* ctx, jobject /*CertPathValidator*/ validator, PAL_X509RevocationMode revocationMode, PAL_X509RevocationFlag revocationFlag) { abort_if_invalid_pointer_argument (ctx); abort_if_invalid_pointer_argument (validator); int32_t ret = FAIL; INIT_LOCALS(loc, certPathFromAnchor, options, checker, result, ex); if (revocationMode == X509RevocationMode_Offline) { // Android does not supply a way to disable OCSP/CRL fetching LOG_INFO("Treating revocation mode 'Offline' as 'Online'."); } jobject certPathToUse = NULL; if (revocationFlag == X509RevocationFlag_EntireChain) { LOG_INFO("Treating revocation flag 'EntireChain' as 'ExcludeRoot'. " "Revocation will be not be checked for root certificate."); certPathToUse = ctx->certPath; } else if (revocationFlag == X509RevocationFlag_EndCertificateOnly) { // List<Certificate> certPathList = certPath.getCertificates(); // int certCount = certPathList.size(); jobject certPathList = (*env)->CallObjectMethod(env, ctx->certPath, g_CertPathGetCertificates); int certCount = (int)(*env)->CallIntMethod(env, certPathList, g_CollectionSize); if (certCount == 0) { // If the chain only consists only of the trust anchor, create a path with just // the trust anchor for revocation checking for end certificate only. This should // still pass normal (non-revocation) validation when it is the only certificate. loc[certPathFromAnchor] = CreateCertPathFromAnchor(env, ctx->trustAnchor); certPathToUse = loc[certPathFromAnchor]; } else { certPathToUse = ctx->certPath; if (AndroidCryptoNative_X509ChainSupportsRevocationOptions()) { // Only add the ONLY_END_ENTITY if we are not just checking the trust anchor. If ONLY_END_ENTITY is // specified, revocation checking will skip the trust anchor even if it is the only certificate. // HashSet<PKIXRevocationChecker.Option> options = new HashSet<PKIXRevocationChecker.Option>(3); // options.add(PKIXRevocationChecker.Option.ONLY_END_ENTITY); loc[options] = (*env)->NewObject(env, g_HashSetClass, g_HashSetCtorWithCapacity, 3); jobject endOnly = (*env)->GetStaticObjectField( env, g_PKIXRevocationCheckerOptionClass, g_PKIXRevocationCheckerOptionOnlyEndEntity); (*env)->CallBooleanMethod(env, loc[options], g_HashSetAdd, endOnly); (*env)->DeleteLocalRef(env, endOnly); } else { LOG_INFO("Treating revocation flag 'EndCertificateOnly' as 'ExcludeRoot'. " "Revocation will be checked for non-end certificates."); } } (*env)->DeleteLocalRef(env, certPathList); } else { abort_unless(revocationFlag == X509RevocationFlag_ExcludeRoot, "revocationFlag must be X509RevocationFlag_ExcludeRoot"); certPathToUse = ctx->certPath; } jobject params = ctx->params; if (AndroidCryptoNative_X509ChainSupportsRevocationOptions()) { // PKIXRevocationChecker checker = validator.getRevocationChecker(); loc[checker] = (*env)->CallObjectMethod(env, validator, g_CertPathValidatorGetRevocationChecker); ON_EXCEPTION_PRINT_AND_GOTO(cleanup); // Set any specific options if (loc[options] != NULL) { // checker.setOptions(options); (*env)->CallVoidMethod(env, loc[checker], g_PKIXRevocationCheckerSetOptions, loc[options]); } // params.addCertPathChecker(checker); (*env)->CallVoidMethod(env, params, g_PKIXBuilderParametersAddCertPathChecker, loc[checker]); } // params.setRevocationEnabled(true); // PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult)validator.validate(certPathToUse, params); (*env)->CallVoidMethod(env, params, g_PKIXBuilderParametersSetRevocationEnabled, true); loc[result] = (*env)->CallObjectMethod(env, validator, g_CertPathValidatorValidate, certPathToUse, params); if (TryGetJNIException(env, &loc[ex], false /*printException*/)) { if (ctx->revocationErrorList == NULL) { ctx->revocationErrorList = ToGRef(env, (*env)->NewObject(env, g_ArrayListClass, g_ArrayListCtor)); } (*env)->CallBooleanMethod(env, ctx->revocationErrorList, g_ArrayListAdd, loc[ex]); } ret = SUCCESS; cleanup: RELEASE_LOCALS(loc, env); return ret; } int32_t AndroidCryptoNative_X509ChainValidate(X509ChainContext* ctx, PAL_X509RevocationMode revocationMode, PAL_X509RevocationFlag revocationFlag, bool* checkedRevocation) { abort_if_invalid_pointer_argument (ctx); abort_if_invalid_pointer_argument (checkedRevocation); JNIEnv* env = GetJNIEnv(); *checkedRevocation = false; int32_t ret = FAIL; INIT_LOCALS(loc, validatorType, validator, result, ex); // String validatorType = "PKIX"; // CertPathValidator validator = CertPathValidator.getInstance(validatorType); loc[validatorType] = make_java_string(env, "PKIX"); loc[validator] = (*env)->CallStaticObjectMethod( env, g_CertPathValidatorClass, g_CertPathValidatorGetInstance, loc[validatorType]); ON_EXCEPTION_PRINT_AND_GOTO(cleanup); // PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult)validator.validate(certPath, params); loc[result] = (*env)->CallObjectMethod(env, loc[validator], g_CertPathValidatorValidate, ctx->certPath, ctx->params); if (TryGetJNIException(env, &loc[ex], false /*printException*/)) { (*env)->CallBooleanMethod(env, ctx->errorList, g_ArrayListAdd, loc[ex]); ret = SUCCESS; } else if (revocationMode != X509RevocationMode_NoCheck) { ret = ValidateWithRevocation(env, ctx, loc[validator], revocationMode, revocationFlag); *checkedRevocation = true; } else { ret = SUCCESS; } cleanup: RELEASE_LOCALS(loc, env); return ret; }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/pal/src/libunwind/src/x86/Lapply_reg_state.c
#define UNW_LOCAL_ONLY #include <libunwind.h> #if defined(UNW_LOCAL_ONLY) && !defined(UNW_REMOTE_ONLY) #include "Gapply_reg_state.c" #endif
#define UNW_LOCAL_ONLY #include <libunwind.h> #if defined(UNW_LOCAL_ONLY) && !defined(UNW_REMOTE_ONLY) #include "Gapply_reg_state.c" #endif
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/vm/object.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // OBJECT.H // // Definitions of a Com+ Object // // See code:EEStartup#TableOfContents for overview #ifndef _OBJECT_H_ #define _OBJECT_H_ #include "util.hpp" #include "syncblk.h" #include "gcdesc.h" #include "specialstatics.h" #include "sstring.h" #include "daccess.h" #include "fcall.h" extern "C" void __fastcall ZeroMemoryInGCHeap(void*, size_t); void ErectWriteBarrierForMT(MethodTable **dst, MethodTable *ref); /* #ObjectModel * COM+ Internal Object Model * * * Object - This is the common base part to all COM+ objects * | it contains the MethodTable pointer and the * | sync block index, which is at a negative offset * | * +-- code:StringObject - String objects are specialized objects for string * | storage/retrieval for higher performance (UCS-2 / UTF-16 data) * | * +-- code:Utf8StringObject - String objects are specialized objects for string * | storage/retrieval for higher performance (UTF-8 data) * | * +-- BaseObjectWithCachedData - Object Plus one object field for caching. * | | * | +- ReflectClassBaseObject - The base object for the RuntimeType class * | +- ReflectMethodObject - The base object for the RuntimeMethodInfo class * | +- ReflectFieldObject - The base object for the RtFieldInfo class * | * +-- code:ArrayBase - Base portion of all arrays * | | * | +- I1Array - Base type arrays * | | I2Array * | | ... * | | * | +- PtrArray - Array of OBJECTREFs, different than base arrays because of pObjectClass * | * +-- code:AssemblyBaseObject - The base object for the class Assembly * * * PLEASE NOTE THE FOLLOWING WHEN ADDING A NEW OBJECT TYPE: * * The size of the object in the heap must be able to be computed * very, very quickly for GC purposes. Restrictions on the layout * of the object guarantee this is possible. * * Any object that inherits from Object must be able to * compute its complete size by using the first 4 bytes of * the object following the Object part and constants * reachable from the MethodTable... * * The formula used for this calculation is: * MT->GetBaseSize() + ((OBJECTTYPEREF->GetSizeField() * MT->GetComponentSize()) * * So for Object, since this is of fixed size, the ComponentSize is 0, which makes the right side * of the equation above equal to 0 no matter what the value of GetSizeField(), so the size is just the base size. * */ class MethodTable; class Thread; class BaseDomain; class Assembly; class DomainAssembly; class AssemblyNative; class WaitHandleNative; class ArgDestination; struct RCW; #ifdef TARGET_64BIT #define OBJHEADER_SIZE (sizeof(DWORD) /* m_alignpad */ + sizeof(DWORD) /* m_SyncBlockValue */) #else #define OBJHEADER_SIZE sizeof(DWORD) /* m_SyncBlockValue */ #endif #define OBJECT_SIZE TARGET_POINTER_SIZE /* m_pMethTab */ #define OBJECT_BASESIZE (OBJHEADER_SIZE + OBJECT_SIZE) #ifdef TARGET_64BIT #define ARRAYBASE_SIZE (OBJECT_SIZE /* m_pMethTab */ + sizeof(DWORD) /* m_NumComponents */ + sizeof(DWORD) /* pad */) #else #define ARRAYBASE_SIZE (OBJECT_SIZE /* m_pMethTab */ + sizeof(DWORD) /* m_NumComponents */) #endif #define ARRAYBASE_BASESIZE (OBJHEADER_SIZE + ARRAYBASE_SIZE) // // The generational GC requires that every object be at least 12 bytes // in size. #define MIN_OBJECT_SIZE (2*TARGET_POINTER_SIZE + OBJHEADER_SIZE) #define PTRALIGNCONST (DATA_ALIGNMENT-1) #ifndef PtrAlign #define PtrAlign(size) \ (((size) + PTRALIGNCONST) & (~PTRALIGNCONST)) #endif //!PtrAlign // code:Object is the respesentation of an managed object on the GC heap. // // See code:#ObjectModel for some important subclasses of code:Object // // The only fields mandated by all objects are // // * a pointer to the code:MethodTable at offset 0 // * a poiner to a code:ObjHeader at a negative offset. This is often zero. It holds information that // any addition information that we might need to attach to arbitrary objects. // class Object { protected: PTR_MethodTable m_pMethTab; protected: Object() { LIMITED_METHOD_CONTRACT; }; ~Object() { LIMITED_METHOD_CONTRACT; }; public: MethodTable *RawGetMethodTable() const { return m_pMethTab; } #ifndef DACCESS_COMPILE void RawSetMethodTable(MethodTable *pMT) { LIMITED_METHOD_CONTRACT; m_pMethTab = pMT; } VOID SetMethodTable(MethodTable *pMT) { WRAPPER_NO_CONTRACT; RawSetMethodTable(pMT); } VOID SetMethodTableForUOHObject(MethodTable *pMT) { WRAPPER_NO_CONTRACT; // This function must be used if the allocation occurs on a UOH heap, and the method table might be a collectible type ErectWriteBarrierForMT(&m_pMethTab, pMT); } #endif //!DACCESS_COMPILE #define MARKED_BIT 0x1 PTR_MethodTable GetMethodTable() const { LIMITED_METHOD_DAC_CONTRACT; #ifndef DACCESS_COMPILE // We should always use GetGCSafeMethodTable() if we're running during a GC. // If the mark bit is set then we're running during a GC _ASSERTE((dac_cast<TADDR>(m_pMethTab) & MARKED_BIT) == 0); return m_pMethTab; #else //DACCESS_COMPILE //@dbgtodo dharvey Make this a type which supports bitwise and operations //when available return PTR_MethodTable((dac_cast<TADDR>(m_pMethTab)) & (~MARKED_BIT)); #endif //DACCESS_COMPILE } DPTR(PTR_MethodTable) GetMethodTablePtr() const { LIMITED_METHOD_CONTRACT; return dac_cast<DPTR(PTR_MethodTable)>(PTR_HOST_MEMBER_TADDR(Object, this, m_pMethTab)); } TypeHandle GetTypeHandle(); // Methods used to determine if an object supports a given interface. static BOOL SupportsInterface(OBJECTREF pObj, MethodTable *pInterfaceMT); inline DWORD GetNumComponents(); inline SIZE_T GetSize(); CGCDesc* GetSlotMap() { WRAPPER_NO_CONTRACT; return( CGCDesc::GetCGCDescFromMT(GetMethodTable())); } // Sync Block & Synchronization services // Access the ObjHeader which is at a negative offset on the object (because of // cache lines) PTR_ObjHeader GetHeader() { LIMITED_METHOD_DAC_CONTRACT; return dac_cast<PTR_ObjHeader>(this) - 1; } // Get the current address of the object (works for debug refs, too.) PTR_BYTE GetAddress() { LIMITED_METHOD_DAC_CONTRACT; return dac_cast<PTR_BYTE>(this); } #ifdef _DEBUG // TRUE if the header has a real SyncBlockIndex (i.e. it has an entry in the // SyncTable, though it doesn't necessarily have an entry in the SyncBlockCache) BOOL HasEmptySyncBlockInfo() { WRAPPER_NO_CONTRACT; return GetHeader()->HasEmptySyncBlockInfo(); } #endif // retrieve or allocate a sync block for this object SyncBlock *GetSyncBlock() { WRAPPER_NO_CONTRACT; return GetHeader()->GetSyncBlock(); } DWORD GetSyncBlockIndex() { WRAPPER_NO_CONTRACT; return GetHeader()->GetSyncBlockIndex(); } // DO NOT ADD ANY ASSERTS TO THIS METHOD. // DO NOT USE THIS METHOD. // Yes folks, for better or worse the debugger pokes supposed object addresses // to try to see if objects are valid, possibly firing an AccessViolation or worse, // and then catches the AV and reports a failure to the debug client. This makes // the debugger slightly more robust should any corrupted object references appear // in a session. Thus it is "correct" behaviour for this to AV when used with // an invalid object pointer, and incorrect behaviour for it to // assert. BOOL ValidateObjectWithPossibleAV(); // Validate an object ref out of the VerifyHeap routine in the GC void ValidateHeap(BOOL bDeep=TRUE); PTR_SyncBlock PassiveGetSyncBlock() { LIMITED_METHOD_DAC_CONTRACT; return GetHeader()->PassiveGetSyncBlock(); } static DWORD ComputeHashCode(); #ifndef DACCESS_COMPILE INT32 GetHashCodeEx(); #endif // #ifndef DACCESS_COMPILE // Synchronization #ifndef DACCESS_COMPILE void EnterObjMonitor() { WRAPPER_NO_CONTRACT; GetHeader()->EnterObjMonitor(); } BOOL TryEnterObjMonitor(INT32 timeOut = 0) { WRAPPER_NO_CONTRACT; return GetHeader()->TryEnterObjMonitor(timeOut); } bool TryEnterObjMonitorSpinHelper(); FORCEINLINE AwareLock::EnterHelperResult EnterObjMonitorHelper(Thread* pCurThread) { WRAPPER_NO_CONTRACT; return GetHeader()->EnterObjMonitorHelper(pCurThread); } FORCEINLINE AwareLock::EnterHelperResult EnterObjMonitorHelperSpin(Thread* pCurThread) { WRAPPER_NO_CONTRACT; return GetHeader()->EnterObjMonitorHelperSpin(pCurThread); } BOOL LeaveObjMonitor() { WRAPPER_NO_CONTRACT; return GetHeader()->LeaveObjMonitor(); } // should be called only from unwind code; used in the // case where EnterObjMonitor failed to allocate the // sync-object. BOOL LeaveObjMonitorAtException() { WRAPPER_NO_CONTRACT; return GetHeader()->LeaveObjMonitorAtException(); } FORCEINLINE AwareLock::LeaveHelperAction LeaveObjMonitorHelper(Thread* pCurThread) { WRAPPER_NO_CONTRACT; return GetHeader()->LeaveObjMonitorHelper(pCurThread); } // Returns TRUE if the lock is owned and FALSE otherwise // threadId is set to the ID (Thread::GetThreadId()) of the thread which owns the lock // acquisitionCount is set to the number of times the lock needs to be released before // it is unowned BOOL GetThreadOwningMonitorLock(DWORD *pThreadId, DWORD *pAcquisitionCount) { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; return GetHeader()->GetThreadOwningMonitorLock(pThreadId, pAcquisitionCount); } #endif // #ifndef DACCESS_COMPILE BOOL Wait(INT32 timeOut) { WRAPPER_NO_CONTRACT; return GetHeader()->Wait(timeOut); } void Pulse() { WRAPPER_NO_CONTRACT; GetHeader()->Pulse(); } void PulseAll() { WRAPPER_NO_CONTRACT; GetHeader()->PulseAll(); } PTR_VOID UnBox(); // if it is a value class, get the pointer to the first field PTR_BYTE GetData(void) { LIMITED_METHOD_CONTRACT; SUPPORTS_DAC; return dac_cast<PTR_BYTE>(this) + sizeof(Object); } static UINT GetOffsetOfFirstField() { LIMITED_METHOD_CONTRACT; return sizeof(Object); } DWORD GetOffset32(DWORD dwOffset) { WRAPPER_NO_CONTRACT; return * PTR_DWORD(GetData() + dwOffset); } USHORT GetOffset16(DWORD dwOffset) { WRAPPER_NO_CONTRACT; return * PTR_USHORT(GetData() + dwOffset); } BYTE GetOffset8(DWORD dwOffset) { WRAPPER_NO_CONTRACT; return * PTR_BYTE(GetData() + dwOffset); } __int64 GetOffset64(DWORD dwOffset) { WRAPPER_NO_CONTRACT; return (__int64) * PTR_ULONG64(GetData() + dwOffset); } void *GetPtrOffset(DWORD dwOffset) { WRAPPER_NO_CONTRACT; return (void *)(TADDR)*PTR_TADDR(GetData() + dwOffset); } #ifndef DACCESS_COMPILE void SetOffsetObjectRef(DWORD dwOffset, size_t dwValue); void SetOffsetPtr(DWORD dwOffset, LPVOID value) { WRAPPER_NO_CONTRACT; *(LPVOID *) &GetData()[dwOffset] = value; } void SetOffset32(DWORD dwOffset, DWORD dwValue) { WRAPPER_NO_CONTRACT; *(DWORD *) &GetData()[dwOffset] = dwValue; } void SetOffset16(DWORD dwOffset, DWORD dwValue) { WRAPPER_NO_CONTRACT; *(USHORT *) &GetData()[dwOffset] = (USHORT) dwValue; } void SetOffset8(DWORD dwOffset, DWORD dwValue) { WRAPPER_NO_CONTRACT; *(BYTE *) &GetData()[dwOffset] = (BYTE) dwValue; } void SetOffset64(DWORD dwOffset, __int64 qwValue) { WRAPPER_NO_CONTRACT; *(__int64 *) &GetData()[dwOffset] = qwValue; } #endif // #ifndef DACCESS_COMPILE VOID Validate(BOOL bDeep = TRUE, BOOL bVerifyNextHeader = TRUE, BOOL bVerifySyncBlock = TRUE); PTR_MethodTable GetGCSafeMethodTable() const { LIMITED_METHOD_CONTRACT; SUPPORTS_DAC; // lose GC marking bit and the reserved bit // A method table pointer should always be aligned. During GC we set the least // significant bit for marked objects, and the second to least significant // bit is reserved. So if we want the actual MT pointer during a GC // we must zero out the lowest 2 bits on 32-bit and 3 bits on 64-bit. #ifdef TARGET_64BIT return dac_cast<PTR_MethodTable>((dac_cast<TADDR>(m_pMethTab)) & ~((UINT_PTR)7)); #else return dac_cast<PTR_MethodTable>((dac_cast<TADDR>(m_pMethTab)) & ~((UINT_PTR)3)); #endif //TARGET_64BIT } // There are some cases where it is unsafe to get the type handle during a GC. // This occurs when the type has already been unloaded as part of an in-progress appdomain shutdown. TypeHandle GetGCSafeTypeHandleIfPossible() const; inline TypeHandle GetGCSafeTypeHandle() const; #ifdef DACCESS_COMPILE void EnumMemoryRegions(void); #endif private: VOID ValidateInner(BOOL bDeep, BOOL bVerifyNextHeader, BOOL bVerifySyncBlock); }; /* * Object ref setting routines. You must use these to do * proper write barrier support. */ // SetObjectReference sets an OBJECTREF field void SetObjectReferenceUnchecked(OBJECTREF *dst,OBJECTREF ref); #ifdef _DEBUG void EnableStressHeapHelper(); #endif //Used to clear the object reference inline void ClearObjectReference(OBJECTREF* dst) { LIMITED_METHOD_CONTRACT; *(void**)(dst) = NULL; } // CopyValueClass sets a value class field void STDCALL CopyValueClassUnchecked(void* dest, void* src, MethodTable *pMT); void STDCALL CopyValueClassArgUnchecked(ArgDestination *argDest, void* src, MethodTable *pMT, int destOffset); inline void InitValueClass(void *dest, MethodTable *pMT) { WRAPPER_NO_CONTRACT; ZeroMemoryInGCHeap(dest, pMT->GetNumInstanceFieldBytes()); } // Initialize value class argument void InitValueClassArg(ArgDestination *argDest, MethodTable *pMT); #define SetObjectReference(_d,_r) SetObjectReferenceUnchecked(_d, _r) #define CopyValueClass(_d,_s,_m) CopyValueClassUnchecked(_d,_s,_m) #define CopyValueClassArg(_d,_s,_m,_o) CopyValueClassArgUnchecked(_d,_s,_m,_o) #include <pshpack4.h> // There are two basic kinds of array layouts in COM+ // ELEMENT_TYPE_ARRAY - a multidimensional array with lower bounds on the dims // ELMENNT_TYPE_SZARRAY - A zero based single dimensional array // // In addition the layout of an array in memory is also affected by // whether the method table is shared (eg in the case of arrays of object refs) // or not. In the shared case, the array has to hold the type handle of // the element type. // // ArrayBase encapuslates all of these details. In theory you should never // have to peek inside this abstraction // class ArrayBase : public Object { friend class GCHeap; friend class CObjectHeader; friend class Object; friend OBJECTREF AllocateSzArray(MethodTable *pArrayMT, INT32 length, GC_ALLOC_FLAGS flags); friend OBJECTREF AllocateArrayEx(MethodTable *pArrayMT, INT32 *pArgs, DWORD dwNumArgs, GC_ALLOC_FLAGS flags); friend FCDECL2(Object*, JIT_NewArr1VC_MP_FastPortable, CORINFO_CLASS_HANDLE arrayMT, INT_PTR size); friend FCDECL2(Object*, JIT_NewArr1OBJ_MP_FastPortable, CORINFO_CLASS_HANDLE arrayMT, INT_PTR size); friend class JIT_TrialAlloc; friend class CheckAsmOffsets; friend struct _DacGlobals; private: // This MUST be the first field, so that it directly follows Object. This is because // Object::GetSize() looks at m_NumComponents even though it may not be an array (the // values is shifted out if not an array, so it's ok). DWORD m_NumComponents; #ifdef TARGET_64BIT DWORD pad; #endif // TARGET_64BIT SVAL_DECL(INT32, s_arrayBoundsZero); // = 0 // What comes after this conceputally is: // INT32 bounds[rank]; The bounds are only present for Multidimensional arrays // INT32 lowerBounds[rank]; Valid indexes are lowerBounds[i] <= index[i] < lowerBounds[i] + bounds[i] public: // Get the element type for the array, this works whether the the element // type is stored in the array or not inline TypeHandle GetArrayElementTypeHandle() const; // Get the CorElementType for the elements in the array. Avoids creating a TypeHandle inline CorElementType GetArrayElementType() const; inline unsigned GetRank() const; // Total element count for the array inline DWORD GetNumComponents() const; // Get pointer to elements, handles any number of dimensions PTR_BYTE GetDataPtr(BOOL inGC = FALSE) const { LIMITED_METHOD_CONTRACT; SUPPORTS_DAC; #ifdef _DEBUG #ifndef DACCESS_COMPILE EnableStressHeapHelper(); #endif #endif return dac_cast<PTR_BYTE>(this) + GetDataPtrOffset(inGC ? GetGCSafeMethodTable() : GetMethodTable()); } // The component size is actually 16-bit WORD, but this method is returning SIZE_T to ensure // that SIZE_T is used everywhere for object size computation. It is necessary to support // objects bigger than 2GB. SIZE_T GetComponentSize() const { WRAPPER_NO_CONTRACT; MethodTable * pMT; pMT = GetMethodTable(); _ASSERTE(pMT->HasComponentSize()); return pMT->RawGetComponentSize(); } // Note that this can be a multidimensional array of rank 1 // (for example if we had a 1-D array with lower bounds BOOL IsMultiDimArray() const { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; return(GetMethodTable()->IsMultiDimArray()); } // Get pointer to the beginning of the bounds (counts for each dim) // Works for any array type PTR_INT32 GetBoundsPtr() const { WRAPPER_NO_CONTRACT; MethodTable * pMT = GetMethodTable(); if (pMT->IsMultiDimArray()) { return dac_cast<PTR_INT32>( dac_cast<TADDR>(this) + sizeof(*this)); } else { return dac_cast<PTR_INT32>(PTR_HOST_MEMBER_TADDR(ArrayBase, this, m_NumComponents)); } } // Works for any array type PTR_INT32 GetLowerBoundsPtr() const { WRAPPER_NO_CONTRACT; if (IsMultiDimArray()) { // Lower bounds info is after total bounds info // and total bounds info has rank elements return GetBoundsPtr() + GetRank(); } else return dac_cast<PTR_INT32>(GVAL_ADDR(s_arrayBoundsZero)); } static unsigned GetOffsetOfNumComponents() { LIMITED_METHOD_CONTRACT; return offsetof(ArrayBase, m_NumComponents); } inline static unsigned GetDataPtrOffset(MethodTable* pMT); inline static unsigned GetBoundsOffset(MethodTable* pMT); inline static unsigned GetLowerBoundsOffset(MethodTable* pMT); }; // // Template used to build all the non-object // arrays of a single dimension // template < class KIND > class Array : public ArrayBase { public: typedef DPTR(KIND) PTR_KIND; typedef DPTR(const KIND) PTR_CKIND; KIND m_Array[1]; PTR_KIND GetDirectPointerToNonObjectElements() { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; // return m_Array; return PTR_KIND(GetDataPtr()); // This also handles arrays of dim 1 with lower bounds present } PTR_CKIND GetDirectConstPointerToNonObjectElements() const { WRAPPER_NO_CONTRACT; // return m_Array; return PTR_CKIND(GetDataPtr()); // This also handles arrays of dim 1 with lower bounds present } }; // Warning: Use PtrArray only for single dimensional arrays, not multidim arrays. class PtrArray : public ArrayBase { friend class GCHeap; friend class ClrDataAccess; friend OBJECTREF AllocateArrayEx(MethodTable *pArrayMT, INT32 *pArgs, DWORD dwNumArgs, DWORD flags); friend class JIT_TrialAlloc; friend class CheckAsmOffsets; public: TypeHandle GetArrayElementTypeHandle() { LIMITED_METHOD_CONTRACT; return GetMethodTable()->GetArrayElementTypeHandle(); } PTR_OBJECTREF GetDataPtr() { LIMITED_METHOD_CONTRACT; SUPPORTS_DAC; return dac_cast<PTR_OBJECTREF>(dac_cast<PTR_BYTE>(this) + GetDataOffset()); } static SIZE_T GetDataOffset() { LIMITED_METHOD_CONTRACT; return offsetof(PtrArray, m_Array); } void SetAt(SIZE_T i, OBJECTREF ref) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; _ASSERTE(i < GetNumComponents()); SetObjectReference(m_Array + i, ref); } void ClearAt(SIZE_T i) { WRAPPER_NO_CONTRACT; _ASSERTE(i < GetNumComponents()); ClearObjectReference(m_Array + i); } OBJECTREF GetAt(SIZE_T i) { LIMITED_METHOD_CONTRACT; SUPPORTS_DAC; _ASSERTE(i < GetNumComponents()); // DAC doesn't know the true size of this array // the compiler thinks it is size 1, but really it is size N hanging off the structure #ifndef DACCESS_COMPILE return m_Array[i]; #else TADDR arrayTargetAddress = dac_cast<TADDR>(this) + offsetof(PtrArray, m_Array); __ArrayDPtr<OBJECTREF> targetArray = dac_cast< __ArrayDPtr<OBJECTREF> >(arrayTargetAddress); return targetArray[i]; #endif } friend class StubLinkerCPU; #ifdef FEATURE_ARRAYSTUB_AS_IL friend class ArrayOpLinker; #endif public: OBJECTREF m_Array[1]; }; #define OFFSETOF__PtrArray__m_Array_ ARRAYBASE_SIZE /* Corresponds to the managed Span<T> and ReadOnlySpan<T> types. This should only ever be passed from the managed to the unmanaged world byref, as any copies of this struct made within the unmanaged world will not observe potential GC relocations of the source data. */ template < class KIND > class Span { private: /* Keep fields below in sync with managed Span / ReadOnlySpan layout. */ KIND* _pointer; unsigned int _length; public: // !! CAUTION !! // Caller must take care not to reassign returned reference if this span corresponds // to a managed ReadOnlySpan<T>. If KIND is a reference type, caller must use a // helper like SetObjectReference instead of assigning values directly to the // reference location. KIND& GetAt(SIZE_T index) { LIMITED_METHOD_CONTRACT; SUPPORTS_DAC; _ASSERTE(index < GetLength()); return _pointer[index]; } // Gets the length (in elements) of this span. __inline SIZE_T GetLength() const { return _length; } }; /* a TypedByRef is a structure that is used to implement VB's BYREF variants. it is basically a tuple of an address of some data along with a TypeHandle that indicates the type of the address */ class TypedByRef { public: PTR_VOID data; TypeHandle type; }; typedef DPTR(TypedByRef) PTR_TypedByRef; typedef Array<I1> I1Array; typedef Array<I2> I2Array; typedef Array<I4> I4Array; typedef Array<I8> I8Array; typedef Array<R4> R4Array; typedef Array<R8> R8Array; typedef Array<U1> U1Array; typedef Array<U1> BOOLArray; typedef Array<U2> U2Array; typedef Array<WCHAR> CHARArray; typedef Array<U4> U4Array; typedef Array<U8> U8Array; typedef Array<UPTR> UPTRArray; typedef PtrArray PTRArray; typedef DPTR(I1Array) PTR_I1Array; typedef DPTR(I2Array) PTR_I2Array; typedef DPTR(I4Array) PTR_I4Array; typedef DPTR(I8Array) PTR_I8Array; typedef DPTR(R4Array) PTR_R4Array; typedef DPTR(R8Array) PTR_R8Array; typedef DPTR(U1Array) PTR_U1Array; typedef DPTR(BOOLArray) PTR_BOOLArray; typedef DPTR(U2Array) PTR_U2Array; typedef DPTR(CHARArray) PTR_CHARArray; typedef DPTR(U4Array) PTR_U4Array; typedef DPTR(U8Array) PTR_U8Array; typedef DPTR(UPTRArray) PTR_UPTRArray; typedef DPTR(PTRArray) PTR_PTRArray; class StringObject; #ifdef USE_CHECKED_OBJECTREFS typedef REF<ArrayBase> BASEARRAYREF; typedef REF<I1Array> I1ARRAYREF; typedef REF<I2Array> I2ARRAYREF; typedef REF<I4Array> I4ARRAYREF; typedef REF<I8Array> I8ARRAYREF; typedef REF<R4Array> R4ARRAYREF; typedef REF<R8Array> R8ARRAYREF; typedef REF<U1Array> U1ARRAYREF; typedef REF<BOOLArray> BOOLARRAYREF; typedef REF<U2Array> U2ARRAYREF; typedef REF<U4Array> U4ARRAYREF; typedef REF<U8Array> U8ARRAYREF; typedef REF<UPTRArray> UPTRARRAYREF; typedef REF<CHARArray> CHARARRAYREF; typedef REF<PTRArray> PTRARRAYREF; // Warning: Use PtrArray only for single dimensional arrays, not multidim arrays. typedef REF<StringObject> STRINGREF; #else // USE_CHECKED_OBJECTREFS typedef PTR_ArrayBase BASEARRAYREF; typedef PTR_I1Array I1ARRAYREF; typedef PTR_I2Array I2ARRAYREF; typedef PTR_I4Array I4ARRAYREF; typedef PTR_I8Array I8ARRAYREF; typedef PTR_R4Array R4ARRAYREF; typedef PTR_R8Array R8ARRAYREF; typedef PTR_U1Array U1ARRAYREF; typedef PTR_BOOLArray BOOLARRAYREF; typedef PTR_U2Array U2ARRAYREF; typedef PTR_U4Array U4ARRAYREF; typedef PTR_U8Array U8ARRAYREF; typedef PTR_UPTRArray UPTRARRAYREF; typedef PTR_CHARArray CHARARRAYREF; typedef PTR_PTRArray PTRARRAYREF; // Warning: Use PtrArray only for single dimensional arrays, not multidim arrays. typedef PTR_StringObject STRINGREF; #endif // USE_CHECKED_OBJECTREFS #include <poppack.h> /* * StringObject * * Special String implementation for performance. * * m_StringLength - Length of string in number of WCHARs * m_FirstChar - The string buffer * */ class StringObject : public Object { #ifdef DACCESS_COMPILE friend class ClrDataAccess; #endif friend class GCHeap; friend class JIT_TrialAlloc; friend class CheckAsmOffsets; friend class COMString; private: DWORD m_StringLength; WCHAR m_FirstChar; public: VOID SetStringLength(DWORD len) { LIMITED_METHOD_CONTRACT; _ASSERTE(len >= 0); m_StringLength = len; } protected: StringObject() {LIMITED_METHOD_CONTRACT; } ~StringObject() {LIMITED_METHOD_CONTRACT; } public: static DWORD GetBaseSize(); static SIZE_T GetSize(DWORD stringLength); DWORD GetStringLength() { LIMITED_METHOD_DAC_CONTRACT; return( m_StringLength );} WCHAR* GetBuffer() { LIMITED_METHOD_CONTRACT; return (WCHAR*)( dac_cast<TADDR>(this) + offsetof(StringObject, m_FirstChar) ); } static UINT GetBufferOffset() { LIMITED_METHOD_DAC_CONTRACT; return (UINT)(offsetof(StringObject, m_FirstChar)); } static UINT GetStringLengthOffset() { LIMITED_METHOD_CONTRACT; return (UINT)(offsetof(StringObject, m_StringLength)); } VOID GetSString(SString &result) { WRAPPER_NO_CONTRACT; result.Set(GetBuffer(), GetStringLength()); } //======================================================================== // Creates a System.String object. All the functions that take a length // or a count of bytes will add the null terminator after length // characters. So this means that if you have a string that has 5 // characters and the null terminator you should pass in 5 and NOT 6. //======================================================================== static STRINGREF NewString(int length); static STRINGREF NewString(int length, BOOL bHasTrailByte); static STRINGREF NewString(const WCHAR *pwsz); static STRINGREF NewString(const WCHAR *pwsz, int length); static STRINGREF NewString(LPCUTF8 psz); static STRINGREF NewString(LPCUTF8 psz, int cBytes); static STRINGREF GetEmptyString(); static STRINGREF* GetEmptyStringRefPtr(); static STRINGREF* InitEmptyStringRefPtr(); BOOL HasTrailByte(); BOOL GetTrailByte(BYTE *bTrailByte); BOOL SetTrailByte(BYTE bTrailByte); static BOOL CaseInsensitiveCompHelper(_In_reads_(aLength) WCHAR * strA, _In_z_ INT8 * strB, int aLength, int bLength, int *result); /*=================RefInterpretGetStringValuesDangerousForGC====================== **N.B.: This perfoms no range checking and relies on the caller to have done this. **Args: (IN)ref -- the String to be interpretted. ** (OUT)chars -- a pointer to the characters in the buffer. ** (OUT)length -- a pointer to the length of the buffer. **Returns: void. **Exceptions: None. ==============================================================================*/ // !!!! If you use this function, you have to be careful because chars is a pointer // !!!! to the data buffer of ref. If GC happens after this call, you need to make // !!!! sure that you have a pin handle on ref, or use GCPROTECT_BEGINPINNING on ref. void RefInterpretGetStringValuesDangerousForGC(_Outptr_result_buffer_(*length + 1) WCHAR **chars, int *length) { WRAPPER_NO_CONTRACT; _ASSERTE(GetGCSafeMethodTable() == g_pStringClass); *length = GetStringLength(); *chars = GetBuffer(); #ifdef _DEBUG EnableStressHeapHelper(); #endif } private: static STRINGREF* EmptyStringRefPtr; }; /*================================GetEmptyString================================ **Get a reference to the empty string. If we haven't already gotten one, we **query the String class for a pointer to the empty string that we know was **created at startup. ** **Args: None **Returns: A STRINGREF to the EmptyString **Exceptions: None ==============================================================================*/ inline STRINGREF StringObject::GetEmptyString() { CONTRACTL { THROWS; MODE_COOPERATIVE; GC_TRIGGERS; } CONTRACTL_END; STRINGREF* refptr = EmptyStringRefPtr; //If we've never gotten a reference to the EmptyString, we need to go get one. if (refptr==NULL) { refptr = InitEmptyStringRefPtr(); } //We've already have a reference to the EmptyString, so we can just return it. return *refptr; } inline STRINGREF* StringObject::GetEmptyStringRefPtr() { CONTRACTL { THROWS; MODE_ANY; GC_TRIGGERS; } CONTRACTL_END; STRINGREF* refptr = EmptyStringRefPtr; //If we've never gotten a reference to the EmptyString, we need to go get one. if (refptr==NULL) { refptr = InitEmptyStringRefPtr(); } //We've already have a reference to the EmptyString, so we can just return it. return refptr; } // This is used to account for the remoting cache on RuntimeType, // RuntimeMethodInfo, and RtFieldInfo. class BaseObjectWithCachedData : public Object { }; // This is the Class version of the Reflection object. // A Class has adddition information. // For a ReflectClassBaseObject the m_pData is a pointer to a FieldDesc array that // contains all of the final static primitives if its defined. // m_cnt = the number of elements defined in the m_pData FieldDesc array. -1 means // this hasn't yet been defined. class ReflectClassBaseObject : public BaseObjectWithCachedData { friend class CoreLibBinder; protected: OBJECTREF m_keepalive; OBJECTREF m_cache; TypeHandle m_typeHandle; #ifdef _DEBUG void TypeCheck() { CONTRACTL { NOTHROW; MODE_COOPERATIVE; GC_NOTRIGGER; } CONTRACTL_END; MethodTable *pMT = GetMethodTable(); while (pMT != g_pRuntimeTypeClass && pMT != NULL) { pMT = pMT->GetParentMethodTable(); } _ASSERTE(pMT == g_pRuntimeTypeClass); } #endif // _DEBUG public: void SetType(TypeHandle type) { CONTRACTL { NOTHROW; MODE_COOPERATIVE; GC_NOTRIGGER; } CONTRACTL_END; INDEBUG(TypeCheck()); m_typeHandle = type; } void SetKeepAlive(OBJECTREF keepalive) { CONTRACTL { NOTHROW; MODE_COOPERATIVE; GC_NOTRIGGER; } CONTRACTL_END; INDEBUG(TypeCheck()); SetObjectReference(&m_keepalive, keepalive); } TypeHandle GetType() { CONTRACTL { NOTHROW; MODE_COOPERATIVE; GC_NOTRIGGER; } CONTRACTL_END; INDEBUG(TypeCheck()); return m_typeHandle; } }; // This is the Method version of the Reflection object. // A Method has adddition information. // m_pMD - A pointer to the actual MethodDesc of the method. // m_object - a field that has a reference type in it. Used only for RuntimeMethodInfoStub to keep the real type alive. // This structure matches the structure up to the m_pMD for several different managed types. // (RuntimeConstructorInfo, RuntimeMethodInfo, and RuntimeMethodInfoStub). These types are unrelated in the type // system except that they all implement a particular interface. It is important that that interface is not attached to any // type that does not sufficiently match this data structure. class ReflectMethodObject : public BaseObjectWithCachedData { friend class CoreLibBinder; protected: OBJECTREF m_object; OBJECTREF m_empty1; OBJECTREF m_empty2; OBJECTREF m_empty3; OBJECTREF m_empty4; OBJECTREF m_empty5; OBJECTREF m_empty6; OBJECTREF m_empty7; MethodDesc * m_pMD; public: void SetMethod(MethodDesc *pMethod) { LIMITED_METHOD_CONTRACT; m_pMD = pMethod; } // This must only be called on instances of ReflectMethodObject that are actually RuntimeMethodInfoStub void SetKeepAlive(OBJECTREF keepalive) { WRAPPER_NO_CONTRACT; SetObjectReference(&m_object, keepalive); } MethodDesc *GetMethod() { LIMITED_METHOD_CONTRACT; return m_pMD; } }; // This is the Field version of the Reflection object. // A Method has adddition information. // m_pFD - A pointer to the actual MethodDesc of the method. // m_object - a field that has a reference type in it. Used only for RuntimeFieldInfoStub to keep the real type alive. // This structure matches the structure up to the m_pFD for several different managed types. // (RtFieldInfo and RuntimeFieldInfoStub). These types are unrelated in the type // system except that they all implement a particular interface. It is important that that interface is not attached to any // type that does not sufficiently match this data structure. class ReflectFieldObject : public BaseObjectWithCachedData { friend class CoreLibBinder; protected: OBJECTREF m_object; OBJECTREF m_empty1; INT32 m_empty2; OBJECTREF m_empty3; OBJECTREF m_empty4; FieldDesc * m_pFD; public: void SetField(FieldDesc *pField) { LIMITED_METHOD_CONTRACT; m_pFD = pField; } // This must only be called on instances of ReflectFieldObject that are actually RuntimeFieldInfoStub void SetKeepAlive(OBJECTREF keepalive) { WRAPPER_NO_CONTRACT; SetObjectReference(&m_object, keepalive); } FieldDesc *GetField() { LIMITED_METHOD_CONTRACT; return m_pFD; } }; // ReflectModuleBaseObject // This class is the base class for managed Module. // This class will connect the Object back to the underlying VM representation // m_ReflectClass -- This is the real Class that was used for reflection // This class was used to get at this object // m_pData -- this is a generic pointer which usually points CorModule // class ReflectModuleBaseObject : public Object { friend class CoreLibBinder; protected: // READ ME: // Modifying the order or fields of this object may require other changes to the // classlib class definition of this object. OBJECTREF m_runtimeType; OBJECTREF m_runtimeAssembly; void* m_ReflectClass; // Pointer to the ReflectClass structure Module* m_pData; // Pointer to the Module void* m_pGlobals; // Global values.... void* m_pGlobalsFlds; // Global Fields.... protected: ReflectModuleBaseObject() {LIMITED_METHOD_CONTRACT;} ~ReflectModuleBaseObject() {LIMITED_METHOD_CONTRACT;} public: void SetModule(Module* p) { LIMITED_METHOD_CONTRACT; m_pData = p; } Module* GetModule() { LIMITED_METHOD_CONTRACT; return m_pData; } void SetAssembly(OBJECTREF assembly) { WRAPPER_NO_CONTRACT; SetObjectReference(&m_runtimeAssembly, assembly); } }; NOINLINE ReflectModuleBaseObject* GetRuntimeModuleHelper(LPVOID __me, Module *pModule, OBJECTREF keepAlive); #define FC_RETURN_MODULE_OBJECT(pModule, refKeepAlive) FC_INNER_RETURN(ReflectModuleBaseObject*, GetRuntimeModuleHelper(__me, pModule, refKeepAlive)) class SafeHandle; #ifdef USE_CHECKED_OBJECTREFS typedef REF<SafeHandle> SAFEHANDLE; typedef REF<SafeHandle> SAFEHANDLEREF; #else // USE_CHECKED_OBJECTREFS typedef SafeHandle * SAFEHANDLE; typedef SafeHandle * SAFEHANDLEREF; #endif // USE_CHECKED_OBJECTREFS class ThreadBaseObject; class SynchronizationContextObject: public Object { friend class CoreLibBinder; private: // These field are also defined in the managed representation. (SecurityContext.cs)If you // add or change these field you must also change the managed code so that // it matches these. This is necessary so that the object is the proper // size. CLR_BOOL _requireWaitNotification; public: BOOL IsWaitNotificationRequired() const { LIMITED_METHOD_CONTRACT; return _requireWaitNotification; } }; typedef DPTR(class CultureInfoBaseObject) PTR_CultureInfoBaseObject; #ifdef USE_CHECKED_OBJECTREFS typedef REF<SynchronizationContextObject> SYNCHRONIZATIONCONTEXTREF; typedef REF<ExecutionContextObject> EXECUTIONCONTEXTREF; typedef REF<CultureInfoBaseObject> CULTUREINFOBASEREF; typedef REF<ArrayBase> ARRAYBASEREF; #else typedef SynchronizationContextObject* SYNCHRONIZATIONCONTEXTREF; typedef CultureInfoBaseObject* CULTUREINFOBASEREF; typedef PTR_ArrayBase ARRAYBASEREF; #endif // Note that the name must always be "" or "en-US". Other cases and nulls // aren't allowed (we already checked.) __inline bool IsCultureEnglishOrInvariant(LPCWSTR localeName) { LIMITED_METHOD_CONTRACT; if (localeName != NULL && (localeName[0] == W('\0') || wcscmp(localeName, W("en-US")) == 0)) { return true; } return false; } class CultureInfoBaseObject : public Object { friend class CoreLibBinder; private: OBJECTREF _compareInfo; OBJECTREF _textInfo; OBJECTREF _numInfo; OBJECTREF _dateTimeInfo; OBJECTREF _calendar; OBJECTREF _cultureData; OBJECTREF _consoleFallbackCulture; STRINGREF _name; // "real" name - en-US, de-DE_phoneb or fj-FJ STRINGREF _nonSortName; // name w/o sort info (de-DE for de-DE_phoneb) STRINGREF _sortName; // Sort only name (de-DE_phoneb, en-us for fj-fj (w/us sort) CULTUREINFOBASEREF _parent; CLR_BOOL _isReadOnly; CLR_BOOL _isInherited; public: CULTUREINFOBASEREF GetParent() { LIMITED_METHOD_CONTRACT; return _parent; }// GetParent STRINGREF GetName() { LIMITED_METHOD_CONTRACT; return _name; }// GetName }; // class CultureInfoBaseObject typedef DPTR(class ThreadBaseObject) PTR_ThreadBaseObject; class ThreadBaseObject : public Object { friend class ClrDataAccess; friend class ThreadNative; friend class CoreLibBinder; friend class Object; private: // These field are also defined in the managed representation. If you // add or change these field you must also change the managed code so that // it matches these. This is necessary so that the object is the proper // size. The order here must match that order which the loader will choose // when laying out the managed class. Note that the layouts are checked // at run time, not compile time. OBJECTREF m_ExecutionContext; OBJECTREF m_SynchronizationContext; STRINGREF m_Name; OBJECTREF m_StartHelper; // The next field (m_InternalThread) is declared as IntPtr in the managed // definition of Thread. The loader will sort it next. // m_InternalThread is always valid -- unless the thread has finalized and been // resurrected. (The thread stopped running before it was finalized). Thread *m_InternalThread; INT32 m_Priority; // We need to cache the thread id in managed code for perf reasons. INT32 m_ManagedThreadId; // Only used by managed code, see comment there bool m_MayNeedResetForThreadPool; protected: // the ctor and dtor can do no useful work. ThreadBaseObject() {LIMITED_METHOD_CONTRACT;}; ~ThreadBaseObject() {LIMITED_METHOD_CONTRACT;}; public: Thread *GetInternal() { LIMITED_METHOD_CONTRACT; return m_InternalThread; } void SetInternal(Thread *it); void ClearInternal(); INT32 GetManagedThreadId() { LIMITED_METHOD_CONTRACT; return m_ManagedThreadId; } void SetManagedThreadId(INT32 id) { LIMITED_METHOD_CONTRACT; m_ManagedThreadId = id; } STRINGREF GetName() { LIMITED_METHOD_CONTRACT; return m_Name; } OBJECTREF GetSynchronizationContext() { LIMITED_METHOD_CONTRACT; return m_SynchronizationContext; } void InitExisting(); void ResetStartHelper() { LIMITED_METHOD_CONTRACT m_StartHelper = NULL; } void ResetName() { LIMITED_METHOD_CONTRACT; m_Name = NULL; } void SetPriority(INT32 priority) { LIMITED_METHOD_CONTRACT; m_Priority = priority; } INT32 GetPriority() const { LIMITED_METHOD_CONTRACT; return m_Priority; } }; // MarshalByRefObjectBaseObject // This class is the base class for MarshalByRefObject // class MarshalByRefObjectBaseObject : public Object { }; // AssemblyBaseObject // This class is the base class for assemblies // class AssemblyBaseObject : public Object { friend class Assembly; friend class CoreLibBinder; protected: // READ ME: // Modifying the order or fields of this object may require other changes to the // classlib class definition of this object. OBJECTREF m_pModuleEventHandler; // Delegate for 'resolve module' event STRINGREF m_fullname; // Slot for storing assemblies fullname OBJECTREF m_pSyncRoot; // Pointer to loader allocator to keep collectible types alive, and to serve as the syncroot for assembly building in ref.emit DomainAssembly* m_pAssembly; // Pointer to the Assembly Structure protected: AssemblyBaseObject() { LIMITED_METHOD_CONTRACT; } ~AssemblyBaseObject() { LIMITED_METHOD_CONTRACT; } public: void SetAssembly(DomainAssembly* p) { LIMITED_METHOD_CONTRACT; m_pAssembly = p; } DomainAssembly* GetDomainAssembly() { LIMITED_METHOD_CONTRACT; return m_pAssembly; } Assembly* GetAssembly(); void SetSyncRoot(OBJECTREF pSyncRoot) { WRAPPER_NO_CONTRACT; SetObjectReference(&m_pSyncRoot, pSyncRoot); } }; NOINLINE AssemblyBaseObject* GetRuntimeAssemblyHelper(LPVOID __me, DomainAssembly *pAssembly, OBJECTREF keepAlive); #define FC_RETURN_ASSEMBLY_OBJECT(pAssembly, refKeepAlive) FC_INNER_RETURN(AssemblyBaseObject*, GetRuntimeAssemblyHelper(__me, pAssembly, refKeepAlive)) // AssemblyLoadContextBaseObject // This class is the base class for AssemblyLoadContext // #if defined(TARGET_X86) && !defined(TARGET_UNIX) #include "pshpack4.h" #endif // defined(TARGET_X86) && !defined(TARGET_UNIX) class AssemblyLoadContextBaseObject : public Object { friend class CoreLibBinder; protected: // READ ME: // Modifying the order or fields of this object may require other changes to the // classlib class definition of this object. #ifdef TARGET_64BIT OBJECTREF _unloadLock; OBJECTREF _resovlingUnmanagedDll; OBJECTREF _resolving; OBJECTREF _unloading; OBJECTREF _name; INT_PTR _nativeAssemblyLoadContext; int64_t _id; // On 64-bit platforms this is a value type so it is placed after references and pointers DWORD _state; CLR_BOOL _isCollectible; #else // TARGET_64BIT int64_t _id; // On 32-bit platforms this 64-bit value type is larger than a pointer so JIT places it first OBJECTREF _unloadLock; OBJECTREF _resovlingUnmanagedDll; OBJECTREF _resolving; OBJECTREF _unloading; OBJECTREF _name; INT_PTR _nativeAssemblyLoadContext; DWORD _state; CLR_BOOL _isCollectible; #endif // TARGET_64BIT protected: AssemblyLoadContextBaseObject() { LIMITED_METHOD_CONTRACT; } ~AssemblyLoadContextBaseObject() { LIMITED_METHOD_CONTRACT; } public: INT_PTR GetNativeAssemblyBinder() { LIMITED_METHOD_CONTRACT; return _nativeAssemblyLoadContext; } }; #if defined(TARGET_X86) && !defined(TARGET_UNIX) #include "poppack.h" #endif // defined(TARGET_X86) && !defined(TARGET_UNIX) // AssemblyNameBaseObject // This class is the base class for assembly names // class AssemblyNameBaseObject : public Object { friend class AssemblyNative; friend class AppDomainNative; friend class CoreLibBinder; protected: // READ ME: // Modifying the order or fields of this object may require other changes to the // classlib class definition of this object. OBJECTREF _name; U1ARRAYREF _publicKey; U1ARRAYREF _publicKeyToken; OBJECTREF _cultureInfo; OBJECTREF _codeBase; OBJECTREF _version; DWORD _hashAlgorithm; DWORD _versionCompatibility; DWORD _flags; protected: AssemblyNameBaseObject() { LIMITED_METHOD_CONTRACT; } ~AssemblyNameBaseObject() { LIMITED_METHOD_CONTRACT; } public: OBJECTREF GetSimpleName() { LIMITED_METHOD_CONTRACT; return _name; } U1ARRAYREF GetPublicKey() { LIMITED_METHOD_CONTRACT; return _publicKey; } U1ARRAYREF GetPublicKeyToken() { LIMITED_METHOD_CONTRACT; return _publicKeyToken; } OBJECTREF GetCultureInfo() { LIMITED_METHOD_CONTRACT; return _cultureInfo; } OBJECTREF GetAssemblyCodeBase() { LIMITED_METHOD_CONTRACT; return _codeBase; } OBJECTREF GetVersion() { LIMITED_METHOD_CONTRACT; return _version; } DWORD GetAssemblyHashAlgorithm() { LIMITED_METHOD_CONTRACT; return _hashAlgorithm; } DWORD GetFlags() { LIMITED_METHOD_CONTRACT; return _flags; } }; // VersionBaseObject // This class is the base class for versions // class VersionBaseObject : public Object { friend class CoreLibBinder; protected: // READ ME: // Modifying the order or fields of this object may require other changes to the // classlib class definition of this object. int m_Major; int m_Minor; int m_Build; int m_Revision; VersionBaseObject() {LIMITED_METHOD_CONTRACT;} ~VersionBaseObject() {LIMITED_METHOD_CONTRACT;} public: int GetMajor() { LIMITED_METHOD_CONTRACT; return m_Major; } int GetMinor() { LIMITED_METHOD_CONTRACT; return m_Minor; } int GetBuild() { LIMITED_METHOD_CONTRACT; return m_Build; } int GetRevision() { LIMITED_METHOD_CONTRACT; return m_Revision; } }; class WeakReferenceObject : public Object { public: Volatile<OBJECTHANDLE> m_Handle; }; #ifdef USE_CHECKED_OBJECTREFS typedef REF<ReflectModuleBaseObject> REFLECTMODULEBASEREF; typedef REF<ReflectClassBaseObject> REFLECTCLASSBASEREF; typedef REF<ReflectMethodObject> REFLECTMETHODREF; typedef REF<ReflectFieldObject> REFLECTFIELDREF; typedef REF<ThreadBaseObject> THREADBASEREF; typedef REF<MarshalByRefObjectBaseObject> MARSHALBYREFOBJECTBASEREF; typedef REF<AssemblyBaseObject> ASSEMBLYREF; typedef REF<AssemblyLoadContextBaseObject> ASSEMBLYLOADCONTEXTREF; typedef REF<AssemblyNameBaseObject> ASSEMBLYNAMEREF; typedef REF<VersionBaseObject> VERSIONREF; typedef REF<WeakReferenceObject> WEAKREFERENCEREF; inline ARG_SLOT ObjToArgSlot(OBJECTREF objRef) { LIMITED_METHOD_CONTRACT; LPVOID v; v = OBJECTREFToObject(objRef); return (ARG_SLOT)(SIZE_T)v; } inline OBJECTREF ArgSlotToObj(ARG_SLOT i) { LIMITED_METHOD_CONTRACT; LPVOID v; v = (LPVOID)(SIZE_T)i; return ObjectToOBJECTREF ((Object*)v); } inline ARG_SLOT StringToArgSlot(STRINGREF sr) { LIMITED_METHOD_CONTRACT; LPVOID v; v = OBJECTREFToObject(sr); return (ARG_SLOT)(SIZE_T)v; } inline STRINGREF ArgSlotToString(ARG_SLOT s) { LIMITED_METHOD_CONTRACT; LPVOID v; v = (LPVOID)(SIZE_T)s; return ObjectToSTRINGREF ((StringObject*)v); } #else // USE_CHECKED_OBJECTREFS typedef PTR_ReflectModuleBaseObject REFLECTMODULEBASEREF; typedef PTR_ReflectClassBaseObject REFLECTCLASSBASEREF; typedef PTR_ReflectMethodObject REFLECTMETHODREF; typedef PTR_ReflectFieldObject REFLECTFIELDREF; typedef PTR_ThreadBaseObject THREADBASEREF; typedef PTR_AssemblyBaseObject ASSEMBLYREF; typedef PTR_AssemblyLoadContextBaseObject ASSEMBLYLOADCONTEXTREF; typedef PTR_AssemblyNameBaseObject ASSEMBLYNAMEREF; #ifndef DACCESS_COMPILE typedef MarshalByRefObjectBaseObject* MARSHALBYREFOBJECTBASEREF; typedef VersionBaseObject* VERSIONREF; typedef WeakReferenceObject* WEAKREFERENCEREF; #endif // #ifndef DACCESS_COMPILE #define ObjToArgSlot(objref) ((ARG_SLOT)(SIZE_T)(objref)) #define ArgSlotToObj(s) ((OBJECTREF)(SIZE_T)(s)) #define StringToArgSlot(objref) ((ARG_SLOT)(SIZE_T)(objref)) #define ArgSlotToString(s) ((STRINGREF)(SIZE_T)(s)) #endif //USE_CHECKED_OBJECTREFS #define PtrToArgSlot(ptr) ((ARG_SLOT)(SIZE_T)(ptr)) #define ArgSlotToPtr(s) ((LPVOID)(SIZE_T)(s)) #define BoolToArgSlot(b) ((ARG_SLOT)(CLR_BOOL)(!!(b))) #define ArgSlotToBool(s) ((BOOL)(s)) STRINGREF AllocateString(SString sstr); CHARARRAYREF AllocateCharArray(DWORD dwArrayLength); #ifdef FEATURE_COMINTEROP //------------------------------------------------------------- // class ComObject, Exposed class __ComObject // // //------------------------------------------------------------- class ComObject : public MarshalByRefObjectBaseObject { friend class CoreLibBinder; protected: ComObject() {LIMITED_METHOD_CONTRACT;}; // don't instantiate this class directly ~ComObject(){LIMITED_METHOD_CONTRACT;}; public: OBJECTREF m_ObjectToDataMap; //-------------------------------------------------------------------- // SupportsInterface static BOOL SupportsInterface(OBJECTREF oref, MethodTable* pIntfTable); //-------------------------------------------------------------------- // SupportsInterface static void ThrowInvalidCastException(OBJECTREF *pObj, MethodTable* pCastToMT); //----------------------------------------------------------------- // GetComIPFromRCW static IUnknown* GetComIPFromRCW(OBJECTREF *pObj, MethodTable* pIntfTable); //----------------------------------------------------------------- // GetComIPFromRCWThrowing static IUnknown* GetComIPFromRCWThrowing(OBJECTREF *pObj, MethodTable* pIntfTable); //----------------------------------------------------------- // create an empty ComObjectRef static OBJECTREF CreateComObjectRef(MethodTable* pMT); //----------------------------------------------------------- // Release all the data associated with the __ComObject. static void ReleaseAllData(OBJECTREF oref); }; #ifdef USE_CHECKED_OBJECTREFS typedef REF<ComObject> COMOBJECTREF; #else typedef ComObject* COMOBJECTREF; #endif //------------------------------------------------------------- // class UnknownWrapper, Exposed class UnknownWrapper // // //------------------------------------------------------------- class UnknownWrapper : public Object { protected: UnknownWrapper(UnknownWrapper &wrap) {LIMITED_METHOD_CONTRACT}; // dissalow copy construction. UnknownWrapper() {LIMITED_METHOD_CONTRACT;}; // don't instantiate this class directly ~UnknownWrapper() {LIMITED_METHOD_CONTRACT;}; OBJECTREF m_WrappedObject; public: OBJECTREF GetWrappedObject() { LIMITED_METHOD_CONTRACT; return m_WrappedObject; } void SetWrappedObject(OBJECTREF pWrappedObject) { LIMITED_METHOD_CONTRACT; m_WrappedObject = pWrappedObject; } }; #ifdef USE_CHECKED_OBJECTREFS typedef REF<UnknownWrapper> UNKNOWNWRAPPEROBJECTREF; #else typedef UnknownWrapper* UNKNOWNWRAPPEROBJECTREF; #endif //------------------------------------------------------------- // class DispatchWrapper, Exposed class DispatchWrapper // // //------------------------------------------------------------- class DispatchWrapper : public Object { protected: DispatchWrapper(DispatchWrapper &wrap) {LIMITED_METHOD_CONTRACT}; // dissalow copy construction. DispatchWrapper() {LIMITED_METHOD_CONTRACT;}; // don't instantiate this class directly ~DispatchWrapper() {LIMITED_METHOD_CONTRACT;}; OBJECTREF m_WrappedObject; public: OBJECTREF GetWrappedObject() { LIMITED_METHOD_CONTRACT; return m_WrappedObject; } void SetWrappedObject(OBJECTREF pWrappedObject) { LIMITED_METHOD_CONTRACT; m_WrappedObject = pWrappedObject; } }; #ifdef USE_CHECKED_OBJECTREFS typedef REF<DispatchWrapper> DISPATCHWRAPPEROBJECTREF; #else typedef DispatchWrapper* DISPATCHWRAPPEROBJECTREF; #endif //------------------------------------------------------------- // class VariantWrapper, Exposed class VARIANTWRAPPEROBJECTREF // // //------------------------------------------------------------- class VariantWrapper : public Object { protected: VariantWrapper(VariantWrapper &wrap) {LIMITED_METHOD_CONTRACT}; // dissalow copy construction. VariantWrapper() {LIMITED_METHOD_CONTRACT}; // don't instantiate this class directly ~VariantWrapper() {LIMITED_METHOD_CONTRACT}; OBJECTREF m_WrappedObject; public: OBJECTREF GetWrappedObject() { LIMITED_METHOD_CONTRACT; return m_WrappedObject; } void SetWrappedObject(OBJECTREF pWrappedObject) { LIMITED_METHOD_CONTRACT; m_WrappedObject = pWrappedObject; } }; #ifdef USE_CHECKED_OBJECTREFS typedef REF<VariantWrapper> VARIANTWRAPPEROBJECTREF; #else typedef VariantWrapper* VARIANTWRAPPEROBJECTREF; #endif //------------------------------------------------------------- // class ErrorWrapper, Exposed class ErrorWrapper // // //------------------------------------------------------------- class ErrorWrapper : public Object { protected: ErrorWrapper(ErrorWrapper &wrap) {LIMITED_METHOD_CONTRACT}; // dissalow copy construction. ErrorWrapper() {LIMITED_METHOD_CONTRACT;}; // don't instantiate this class directly ~ErrorWrapper() {LIMITED_METHOD_CONTRACT;}; INT32 m_ErrorCode; public: INT32 GetErrorCode() { LIMITED_METHOD_CONTRACT; return m_ErrorCode; } void SetErrorCode(int ErrorCode) { LIMITED_METHOD_CONTRACT; m_ErrorCode = ErrorCode; } }; #ifdef USE_CHECKED_OBJECTREFS typedef REF<ErrorWrapper> ERRORWRAPPEROBJECTREF; #else typedef ErrorWrapper* ERRORWRAPPEROBJECTREF; #endif //------------------------------------------------------------- // class CurrencyWrapper, Exposed class CurrencyWrapper // // //------------------------------------------------------------- // Keep this in sync with code:MethodTableBuilder.CheckForSystemTypes where // alignment requirement of the managed System.Decimal structure is computed. #if !defined(ALIGN_ACCESS) && !defined(FEATURE_64BIT_ALIGNMENT) #include <pshpack4.h> #endif // !ALIGN_ACCESS && !FEATURE_64BIT_ALIGNMENT class CurrencyWrapper : public Object { protected: CurrencyWrapper(CurrencyWrapper &wrap) {LIMITED_METHOD_CONTRACT}; // dissalow copy construction. CurrencyWrapper() {LIMITED_METHOD_CONTRACT;}; // don't instantiate this class directly ~CurrencyWrapper() {LIMITED_METHOD_CONTRACT;}; DECIMAL m_WrappedObject; public: DECIMAL GetWrappedObject() { LIMITED_METHOD_CONTRACT; return m_WrappedObject; } void SetWrappedObject(DECIMAL WrappedObj) { LIMITED_METHOD_CONTRACT; m_WrappedObject = WrappedObj; } }; #if !defined(ALIGN_ACCESS) && !defined(FEATURE_64BIT_ALIGNMENT) #include <poppack.h> #endif // !ALIGN_ACCESS && !FEATURE_64BIT_ALIGNMENT #ifdef USE_CHECKED_OBJECTREFS typedef REF<CurrencyWrapper> CURRENCYWRAPPEROBJECTREF; #else typedef CurrencyWrapper* CURRENCYWRAPPEROBJECTREF; #endif //------------------------------------------------------------- // class BStrWrapper, Exposed class BSTRWRAPPEROBJECTREF // // //------------------------------------------------------------- class BStrWrapper : public Object { protected: BStrWrapper(BStrWrapper &wrap) {LIMITED_METHOD_CONTRACT}; // dissalow copy construction. BStrWrapper() {LIMITED_METHOD_CONTRACT}; // don't instantiate this class directly ~BStrWrapper() {LIMITED_METHOD_CONTRACT}; STRINGREF m_WrappedObject; public: STRINGREF GetWrappedObject() { LIMITED_METHOD_CONTRACT; return m_WrappedObject; } void SetWrappedObject(STRINGREF pWrappedObject) { LIMITED_METHOD_CONTRACT; m_WrappedObject = pWrappedObject; } }; #ifdef USE_CHECKED_OBJECTREFS typedef REF<BStrWrapper> BSTRWRAPPEROBJECTREF; #else typedef BStrWrapper* BSTRWRAPPEROBJECTREF; #endif #endif // FEATURE_COMINTEROP class SafeHandle : public Object { friend class CoreLibBinder; private: // READ ME: // Modifying the order or fields of this object may require // other changes to the classlib class definition of this // object or special handling when loading this system class. Volatile<LPVOID> m_handle; Volatile<INT32> m_state; // Combined ref count and closed/disposed state (for atomicity) Volatile<CLR_BOOL> m_ownsHandle; Volatile<CLR_BOOL> m_fullyInitialized; // Did constructor finish? // Describe the bits in the m_state field above. enum StateBits { SH_State_Closed = 0x00000001, SH_State_Disposed = 0x00000002, SH_State_RefCount = 0xfffffffc, SH_RefCountOne = 4, // Amount to increment state field to yield a ref count increment of 1 }; static WORD s_IsInvalidHandleMethodSlot; static WORD s_ReleaseHandleMethodSlot; static void RunReleaseMethod(SafeHandle* psh); BOOL IsFullyInitialized() const { LIMITED_METHOD_CONTRACT; return m_fullyInitialized; } public: static void Init(); // To use the SafeHandle from native, look at the SafeHandleHolder, which // will do the AddRef & Release for you. LPVOID GetHandle() const { LIMITED_METHOD_CONTRACT; _ASSERTE(((unsigned int) m_state) >= SH_RefCountOne); return m_handle; } void AddRef(); void Release(bool fDispose = false); void SetHandle(LPVOID handle); }; void AcquireSafeHandle(SAFEHANDLEREF* s); void ReleaseSafeHandle(SAFEHANDLEREF* s); typedef Holder<SAFEHANDLEREF*, AcquireSafeHandle, ReleaseSafeHandle> SafeHandleHolder; class CriticalHandle : public Object { friend class CoreLibBinder; private: // READ ME: // Modifying the order or fields of this object may require // other changes to the classlib class definition of this // object or special handling when loading this system class. Volatile<LPVOID> m_handle; Volatile<CLR_BOOL> m_isClosed; public: LPVOID GetHandle() const { LIMITED_METHOD_CONTRACT; return m_handle; } static size_t GetHandleOffset() { LIMITED_METHOD_CONTRACT; return offsetof(CriticalHandle, m_handle); } void SetHandle(LPVOID handle) { LIMITED_METHOD_CONTRACT; m_handle = handle; } }; #ifdef USE_CHECKED_OBJECTREFS typedef REF<CriticalHandle> CRITICALHANDLE; typedef REF<CriticalHandle> CRITICALHANDLEREF; #else // USE_CHECKED_OBJECTREFS typedef CriticalHandle * CRITICALHANDLE; typedef CriticalHandle * CRITICALHANDLEREF; #endif // USE_CHECKED_OBJECTREFS // WaitHandleBase // Base class for WaitHandle class WaitHandleBase :public MarshalByRefObjectBaseObject { friend class CoreLibBinder; public: __inline LPVOID GetWaitHandle() { LIMITED_METHOD_CONTRACT; SAFEHANDLEREF safeHandle = (SAFEHANDLEREF)m_safeHandle.LoadWithoutBarrier(); return safeHandle != NULL ? safeHandle->GetHandle() : INVALID_HANDLE_VALUE; } __inline SAFEHANDLEREF GetSafeHandle() {LIMITED_METHOD_CONTRACT; return (SAFEHANDLEREF)m_safeHandle.LoadWithoutBarrier();} private: Volatile<SafeHandle*> m_safeHandle; }; #ifdef USE_CHECKED_OBJECTREFS typedef REF<WaitHandleBase> WAITHANDLEREF; #else // USE_CHECKED_OBJECTREFS typedef WaitHandleBase* WAITHANDLEREF; #endif // USE_CHECKED_OBJECTREFS // This class corresponds to System.MulticastDelegate on the managed side. class DelegateObject : public Object { friend class CheckAsmOffsets; friend class CoreLibBinder; public: BOOL IsWrapperDelegate() { LIMITED_METHOD_CONTRACT; return _methodPtrAux == NULL; } OBJECTREF GetTarget() { LIMITED_METHOD_CONTRACT; return _target; } void SetTarget(OBJECTREF target) { WRAPPER_NO_CONTRACT; SetObjectReference(&_target, target); } static int GetOffsetOfTarget() { LIMITED_METHOD_CONTRACT; return offsetof(DelegateObject, _target); } PCODE GetMethodPtr() { LIMITED_METHOD_CONTRACT; return _methodPtr; } void SetMethodPtr(PCODE methodPtr) { LIMITED_METHOD_CONTRACT; _methodPtr = methodPtr; } static int GetOffsetOfMethodPtr() { LIMITED_METHOD_CONTRACT; return offsetof(DelegateObject, _methodPtr); } PCODE GetMethodPtrAux() { LIMITED_METHOD_CONTRACT; return _methodPtrAux; } void SetMethodPtrAux(PCODE methodPtrAux) { LIMITED_METHOD_CONTRACT; _methodPtrAux = methodPtrAux; } static int GetOffsetOfMethodPtrAux() { LIMITED_METHOD_CONTRACT; return offsetof(DelegateObject, _methodPtrAux); } OBJECTREF GetInvocationList() { LIMITED_METHOD_CONTRACT; return _invocationList; } void SetInvocationList(OBJECTREF invocationList) { WRAPPER_NO_CONTRACT; SetObjectReference(&_invocationList, invocationList); } static int GetOffsetOfInvocationList() { LIMITED_METHOD_CONTRACT; return offsetof(DelegateObject, _invocationList); } INT_PTR GetInvocationCount() { LIMITED_METHOD_CONTRACT; return _invocationCount; } void SetInvocationCount(INT_PTR invocationCount) { LIMITED_METHOD_CONTRACT; _invocationCount = invocationCount; } static int GetOffsetOfInvocationCount() { LIMITED_METHOD_CONTRACT; return offsetof(DelegateObject, _invocationCount); } void SetMethodBase(OBJECTREF newMethodBase) { LIMITED_METHOD_CONTRACT; SetObjectReference((OBJECTREF*)&_methodBase, newMethodBase); } // README: // If you modify the order of these fields, make sure to update the definition in // BCL for this object. private: // System.Delegate OBJECTREF _target; OBJECTREF _methodBase; PCODE _methodPtr; PCODE _methodPtrAux; // System.MulticastDelegate OBJECTREF _invocationList; INT_PTR _invocationCount; }; #define OFFSETOF__DelegateObject__target OBJECT_SIZE /* m_pMethTab */ #define OFFSETOF__DelegateObject__methodPtr (OFFSETOF__DelegateObject__target + TARGET_POINTER_SIZE /* _target */ + TARGET_POINTER_SIZE /* _methodBase */) #define OFFSETOF__DelegateObject__methodPtrAux (OFFSETOF__DelegateObject__methodPtr + TARGET_POINTER_SIZE /* _methodPtr */) #ifdef USE_CHECKED_OBJECTREFS typedef REF<DelegateObject> DELEGATEREF; #else // USE_CHECKED_OBJECTREFS typedef DelegateObject* DELEGATEREF; #endif // USE_CHECKED_OBJECTREFS struct StackTraceElement; class ClrDataAccess; typedef DPTR(StackTraceElement) PTR_StackTraceElement; class StackTraceArray { struct ArrayHeader { size_t m_size; Thread * m_thread; }; typedef DPTR(ArrayHeader) PTR_ArrayHeader; public: StackTraceArray() : m_array(static_cast<I1Array *>(NULL)) { WRAPPER_NO_CONTRACT; } StackTraceArray(I1ARRAYREF array) : m_array(array) { LIMITED_METHOD_CONTRACT; } void Swap(StackTraceArray & rhs) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; SUPPORTS_DAC; I1ARRAYREF t = m_array; m_array = rhs.m_array; rhs.m_array = t; } size_t Size() const { WRAPPER_NO_CONTRACT; if (!m_array) return 0; else return GetSize(); } StackTraceElement const & operator[](size_t index) const; StackTraceElement & operator[](size_t index); void Append(StackTraceElement const * begin, StackTraceElement const * end); I1ARRAYREF Get() const { LIMITED_METHOD_DAC_CONTRACT; return m_array; } // Deep copies the array void CopyFrom(StackTraceArray const & src); private: StackTraceArray(StackTraceArray const & rhs) = delete; StackTraceArray & operator=(StackTraceArray const & rhs) = delete; void Grow(size_t size); void EnsureThreadAffinity(); void CheckState() const; size_t Capacity() const { WRAPPER_NO_CONTRACT; assert(!!m_array); return m_array->GetNumComponents(); } size_t GetSize() const { WRAPPER_NO_CONTRACT; return GetHeader()->m_size; } void SetSize(size_t size) { WRAPPER_NO_CONTRACT; GetHeader()->m_size = size; } Thread * GetObjectThread() const { WRAPPER_NO_CONTRACT; return GetHeader()->m_thread; } void SetObjectThread() { WRAPPER_NO_CONTRACT; GetHeader()->m_thread = GetThread(); } StackTraceElement const * GetData() const { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; return dac_cast<PTR_StackTraceElement>(GetRaw() + sizeof(ArrayHeader)); } PTR_StackTraceElement GetData() { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; return dac_cast<PTR_StackTraceElement>(GetRaw() + sizeof(ArrayHeader)); } I1 const * GetRaw() const { WRAPPER_NO_CONTRACT; assert(!!m_array); return const_cast<I1ARRAYREF &>(m_array)->GetDirectPointerToNonObjectElements(); } PTR_I1 GetRaw() { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; assert(!!m_array); return dac_cast<PTR_I1>(m_array->GetDirectPointerToNonObjectElements()); } ArrayHeader const * GetHeader() const { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; return dac_cast<PTR_ArrayHeader>(GetRaw()); } PTR_ArrayHeader GetHeader() { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; return dac_cast<PTR_ArrayHeader>(GetRaw()); } void SetArray(I1ARRAYREF const & arr) { LIMITED_METHOD_CONTRACT; m_array = arr; } private: // put only things here that can be protected with GCPROTECT I1ARRAYREF m_array; }; #ifdef FEATURE_COLLECTIBLE_TYPES class LoaderAllocatorScoutObject : public Object { friend class CoreLibBinder; friend class LoaderAllocatorObject; protected: LoaderAllocator * m_nativeLoaderAllocator; }; #ifdef USE_CHECKED_OBJECTREFS typedef REF<LoaderAllocatorScoutObject> LOADERALLOCATORSCOUTREF; #else // USE_CHECKED_OBJECTREFS typedef LoaderAllocatorScoutObject* LOADERALLOCATORSCOUTREF; #endif // USE_CHECKED_OBJECTREFS class LoaderAllocatorObject : public Object { friend class CoreLibBinder; public: PTRARRAYREF GetHandleTable() { LIMITED_METHOD_DAC_CONTRACT; return (PTRARRAYREF)m_pSlots; } void SetHandleTable(PTRARRAYREF handleTable) { LIMITED_METHOD_CONTRACT; SetObjectReference(&m_pSlots, (OBJECTREF)handleTable); } INT32 GetSlotsUsed() { LIMITED_METHOD_CONTRACT; return m_slotsUsed; } void SetSlotsUsed(INT32 newSlotsUsed) { LIMITED_METHOD_CONTRACT; m_slotsUsed = newSlotsUsed; } void SetNativeLoaderAllocator(LoaderAllocator * pLoaderAllocator) { LIMITED_METHOD_CONTRACT; m_pLoaderAllocatorScout->m_nativeLoaderAllocator = pLoaderAllocator; } // README: // If you modify the order of these fields, make sure to update the definition in // BCL for this object. protected: LOADERALLOCATORSCOUTREF m_pLoaderAllocatorScout; OBJECTREF m_pSlots; INT32 m_slotsUsed; OBJECTREF m_methodInstantiationsTable; }; #ifdef USE_CHECKED_OBJECTREFS typedef REF<LoaderAllocatorObject> LOADERALLOCATORREF; #else // USE_CHECKED_OBJECTREFS typedef DPTR(LoaderAllocatorObject) PTR_LoaderAllocatorObject; typedef PTR_LoaderAllocatorObject LOADERALLOCATORREF; #endif // USE_CHECKED_OBJECTREFS #endif // FEATURE_COLLECTIBLE_TYPES #if !defined(DACCESS_COMPILE) // Define the lock used to access stacktrace from an exception object EXTERN_C SpinLock g_StackTraceArrayLock; #endif // !defined(DACCESS_COMPILE) // This class corresponds to Exception on the managed side. typedef DPTR(class ExceptionObject) PTR_ExceptionObject; #include "pshpack4.h" class ExceptionObject : public Object { friend class CoreLibBinder; public: void SetHResult(HRESULT hr) { LIMITED_METHOD_CONTRACT; _HResult = hr; } HRESULT GetHResult() { LIMITED_METHOD_CONTRACT; return _HResult; } void SetXCode(DWORD code) { LIMITED_METHOD_CONTRACT; _xcode = code; } DWORD GetXCode() { LIMITED_METHOD_CONTRACT; return _xcode; } void SetXPtrs(void* xptrs) { LIMITED_METHOD_CONTRACT; _xptrs = xptrs; } void* GetXPtrs() { LIMITED_METHOD_CONTRACT; return _xptrs; } void SetStackTrace(I1ARRAYREF stackTrace, PTRARRAYREF dynamicMethodArray); void GetStackTrace(StackTraceArray & stackTrace, PTRARRAYREF * outDynamicMethodArray = NULL) const; I1ARRAYREF GetStackTraceArrayObject() const { LIMITED_METHOD_DAC_CONTRACT; return _stackTrace; } void SetInnerException(OBJECTREF innerException) { WRAPPER_NO_CONTRACT; SetObjectReference((OBJECTREF*)&_innerException, (OBJECTREF)innerException); } OBJECTREF GetInnerException() { LIMITED_METHOD_DAC_CONTRACT; return VolatileLoadWithoutBarrierOBJECTREF(&_innerException); } // Returns the innermost exception object - equivalent of the // managed System.Exception.GetBaseException method. OBJECTREF GetBaseException() { LIMITED_METHOD_CONTRACT; // Loop and get the innermost exception object OBJECTREF oInnerMostException = NULL; OBJECTREF oCurrent = NULL; oCurrent = GetInnerException(); while(oCurrent != NULL) { oInnerMostException = oCurrent; oCurrent = ((ExceptionObject*)(Object *)OBJECTREFToObject(oCurrent))->GetInnerException(); } // return the innermost exception return oInnerMostException; } void SetMessage(STRINGREF message) { WRAPPER_NO_CONTRACT; SetObjectReference((OBJECTREF*)&_message, (OBJECTREF)message); } STRINGREF GetMessage() { LIMITED_METHOD_DAC_CONTRACT; return _message; } void SetStackTraceString(STRINGREF stackTraceString) { WRAPPER_NO_CONTRACT; SetObjectReference((OBJECTREF*)&_stackTraceString, (OBJECTREF)stackTraceString); } STRINGREF GetStackTraceString() { LIMITED_METHOD_DAC_CONTRACT; return _stackTraceString; } STRINGREF GetRemoteStackTraceString() { LIMITED_METHOD_DAC_CONTRACT; return (STRINGREF)VolatileLoadWithoutBarrierOBJECTREF(&_remoteStackTraceString); } void SetHelpURL(STRINGREF helpURL) { WRAPPER_NO_CONTRACT; SetObjectReference((OBJECTREF*)&_helpURL, (OBJECTREF)helpURL); } void SetSource(STRINGREF source) { WRAPPER_NO_CONTRACT; SetObjectReference((OBJECTREF*)&_source, (OBJECTREF)source); } void ClearStackTraceForThrow() { WRAPPER_NO_CONTRACT; SetObjectReference((OBJECTREF*)&_remoteStackTraceString, NULL); SetObjectReference((OBJECTREF*)&_stackTrace, NULL); SetObjectReference((OBJECTREF*)&_stackTraceString, NULL); } void ClearStackTracePreservingRemoteStackTrace() { WRAPPER_NO_CONTRACT; SetObjectReference((OBJECTREF*)&_stackTrace, NULL); SetObjectReference((OBJECTREF*)&_stackTraceString, NULL); } // This method will set the reference to the array // containing the watson bucket information (in byte[] form). void SetWatsonBucketReference(OBJECTREF oWatsonBucketArray) { WRAPPER_NO_CONTRACT; SetObjectReference((OBJECTREF*)&_watsonBuckets, (OBJECTREF)oWatsonBucketArray); } // This method will return the reference to the array // containing the watson buckets U1ARRAYREF GetWatsonBucketReference() { LIMITED_METHOD_CONTRACT; return (U1ARRAYREF)VolatileLoadWithoutBarrierOBJECTREF(&_watsonBuckets); } // This method will return a BOOL to indicate if the // watson buckets are present or not. BOOL AreWatsonBucketsPresent() { LIMITED_METHOD_CONTRACT; return (GetWatsonBucketReference() != NULL)?TRUE:FALSE; } // This method will save the IP to be used for watson bucketing. void SetIPForWatsonBuckets(UINT_PTR ip) { LIMITED_METHOD_CONTRACT; _ipForWatsonBuckets = ip; } // This method will return a BOOL to indicate if Watson bucketing IP // is present (or not). BOOL IsIPForWatsonBucketsPresent() { LIMITED_METHOD_CONTRACT; return (_ipForWatsonBuckets != NULL); } // This method returns the IP for Watson Buckets. UINT_PTR GetIPForWatsonBuckets() { LIMITED_METHOD_CONTRACT; return VolatileLoadWithoutBarrier(&_ipForWatsonBuckets); } // README: // If you modify the order of these fields, make sure to update the definition in // BCL for this object. private: OBJECTREF _exceptionMethod; //Needed for serialization. STRINGREF _message; OBJECTREF _data; OBJECTREF _innerException; STRINGREF _helpURL; I1ARRAYREF _stackTrace; U1ARRAYREF _watsonBuckets; STRINGREF _stackTraceString; //Needed for serialization. STRINGREF _remoteStackTraceString; PTRARRAYREF _dynamicMethods; STRINGREF _source; // Mainly used by VB. UINT_PTR _ipForWatsonBuckets; // Contains the IP of exception for watson bucketing void* _xptrs; INT32 _xcode; INT32 _HResult; }; // Defined in Contracts.cs enum ContractFailureKind { CONTRACT_FAILURE_PRECONDITION = 0, CONTRACT_FAILURE_POSTCONDITION, CONTRACT_FAILURE_POSTCONDITION_ON_EXCEPTION, CONTRACT_FAILURE_INVARIANT, CONTRACT_FAILURE_ASSERT, CONTRACT_FAILURE_ASSUME, }; typedef DPTR(class ContractExceptionObject) PTR_ContractExceptionObject; class ContractExceptionObject : public ExceptionObject { friend class CoreLibBinder; public: ContractFailureKind GetContractFailureKind() { LIMITED_METHOD_CONTRACT; return static_cast<ContractFailureKind>(_Kind); } private: // keep these in sync with ndp/clr/src/bcl/system/diagnostics/contracts/contractsbcl.cs STRINGREF _UserMessage; STRINGREF _Condition; INT32 _Kind; }; #include "poppack.h" #ifdef USE_CHECKED_OBJECTREFS typedef REF<ContractExceptionObject> CONTRACTEXCEPTIONREF; #else // USE_CHECKED_OBJECTREFS typedef PTR_ContractExceptionObject CONTRACTEXCEPTIONREF; #endif // USE_CHECKED_OBJECTREFS //=============================================================================== // #NullableFeature // #NullableArchitecture // // In a nutshell it is counterintuitive to have a boxed Nullable<T>, since a boxed // object already has a representation for null (the null pointer), and having // multiple representations for the 'not present' value just causes grief. Thus the // feature is build make Nullable<T> box to a boxed<T> (not boxed<Nullable<T>). // // We want to do this in a way that does not impact the perf of the runtime in the // non-nullable case. // // To do this we need to // * Modify the boxing helper code:JIT_Box (we don't need a special one because // the JIT inlines the common case, so this only gets call in uncommon cases) // * Make a new helper for the Unbox case (see code:JIT_Unbox_Nullable) // * Plumb the JIT to ask for what kind of Boxing helper is needed // (see code:CEEInfo.getBoxHelper, code:CEEInfo.getUnBoxHelper // * change all the places in the CLR where we box or unbox by hand, and force // them to use code:MethodTable.Box, and code:MethodTable.Unbox which in // turn call code:Nullable.Box and code:Nullable.UnBox, most of these // are in reflection, and remoting (passing and returning value types). // // #NullableVerification // // Sadly, the IL Verifier also needs to know about this change. Basically the 'box' // instruction returns a boxed(T) (not a boxed(Nullable<T>)) for the purposes of // verfication. The JIT finds out what box returns by calling back to the EE with // the code:CEEInfo.getTypeForBox API. // // #NullableDebugging // // Sadly, because the debugger also does its own boxing 'by hand' for expression // evaluation inside visual studio, it measn that debuggers also need to be aware // of the fact that Nullable<T> boxes to a boxed<T>. It is the responcibility of // debuggers to follow this convention (which is why this is sad). // //=============================================================================== // Nullable represents the managed generic value type Nullable<T> // // The runtime has special logic for this value class. When it is boxed // it becomes either null or a boxed T. Similarly a boxed T can be unboxed // either as a T (as normal), or as a Nullable<T> // // See code:Nullable#NullableArchitecture for more. // class Nullable { Nullable(); // This is purposefully undefined. Do not make instances // of this class. public: static void CheckFieldOffsets(TypeHandle nullableType); static BOOL IsNullableType(TypeHandle nullableType); static BOOL IsNullableForType(TypeHandle nullableType, MethodTable* paramMT); static BOOL IsNullableForTypeNoGC(TypeHandle nullableType, MethodTable* paramMT); static OBJECTREF Box(void* src, MethodTable* nullable); static BOOL UnBox(void* dest, OBJECTREF boxedVal, MethodTable* destMT); static BOOL UnBoxNoGC(void* dest, OBJECTREF boxedVal, MethodTable* destMT); static BOOL UnBoxIntoArgNoGC(ArgDestination *argDest, OBJECTREF boxedVal, MethodTable* destMT); static void UnBoxNoCheck(void* dest, OBJECTREF boxedVal, MethodTable* destMT); static OBJECTREF BoxedNullableNull(TypeHandle nullableType) { return 0; } // if 'Obj' is a true boxed nullable, return the form we want (either null or a boxed T) static OBJECTREF NormalizeBox(OBJECTREF obj); static inline CLR_BOOL HasValue(void *src, MethodTable *nullableMT) { Nullable *nullable = (Nullable *)src; return *(nullable->HasValueAddr(nullableMT)); } static inline void *Value(void *src, MethodTable *nullableMT) { Nullable *nullable = (Nullable *)src; return nullable->ValueAddr(nullableMT); } private: static BOOL IsNullableForTypeHelper(MethodTable* nullableMT, MethodTable* paramMT); static BOOL IsNullableForTypeHelperNoGC(MethodTable* nullableMT, MethodTable* paramMT); CLR_BOOL* HasValueAddr(MethodTable* nullableMT); void* ValueAddr(MethodTable* nullableMT); }; #ifdef USE_CHECKED_OBJECTREFS typedef REF<ExceptionObject> EXCEPTIONREF; #else // USE_CHECKED_OBJECTREFS typedef PTR_ExceptionObject EXCEPTIONREF; #endif // USE_CHECKED_OBJECTREFS class GCHeapHashObject : public Object { #ifdef DACCESS_COMPILE friend class ClrDataAccess; #endif friend class GCHeap; friend class JIT_TrialAlloc; friend class CheckAsmOffsets; friend class COMString; friend class CoreLibBinder; private: BASEARRAYREF _data; INT32 _count; INT32 _deletedCount; public: INT32 GetCount() { LIMITED_METHOD_CONTRACT; return _count; } void IncrementCount(bool replacingDeletedItem) { LIMITED_METHOD_CONTRACT; ++_count; if (replacingDeletedItem) --_deletedCount; } void DecrementCount(bool deletingItem) { LIMITED_METHOD_CONTRACT; --_count; if (deletingItem) ++_deletedCount; } INT32 GetDeletedCount() { LIMITED_METHOD_CONTRACT; return _deletedCount; } void SetDeletedCountToZero() { LIMITED_METHOD_CONTRACT; _deletedCount = 0; } INT32 GetCapacity() { LIMITED_METHOD_CONTRACT; if (_data == NULL) return 0; else return (_data->GetNumComponents()); } BASEARRAYREF GetData() { LIMITED_METHOD_CONTRACT; return _data; } void SetTable(BASEARRAYREF data) { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_COOPERATIVE; SetObjectReference((OBJECTREF*)&_data, (OBJECTREF)data); } protected: GCHeapHashObject() {LIMITED_METHOD_CONTRACT; } ~GCHeapHashObject() {LIMITED_METHOD_CONTRACT; } }; typedef DPTR(GCHeapHashObject) PTR_GCHeapHashObject; #ifdef USE_CHECKED_OBJECTREFS typedef REF<GCHeapHashObject> GCHEAPHASHOBJECTREF; #else // USE_CHECKED_OBJECTREFS typedef PTR_GCHeapHashObject GCHEAPHASHOBJECTREF; #endif // USE_CHECKED_OBJECTREFS class LAHashDependentHashTrackerObject : public Object { #ifdef DACCESS_COMPILE friend class ClrDataAccess; #endif friend class CheckAsmOffsets; friend class CoreLibBinder; private: OBJECTHANDLE _dependentHandle; LoaderAllocator* _loaderAllocator; public: bool IsLoaderAllocatorLive(); bool IsTrackerFor(LoaderAllocator *pLoaderAllocator) { if (pLoaderAllocator != _loaderAllocator) return false; return IsLoaderAllocatorLive(); } void GetDependentAndLoaderAllocator(OBJECTREF *pLoaderAllocatorRef, GCHEAPHASHOBJECTREF *pGCHeapHash); // Be careful with this. This isn't safe to use unless something is keeping the LoaderAllocator live, or there is no intention to dereference this pointer LoaderAllocator* GetLoaderAllocatorUnsafe() { return _loaderAllocator; } void Init(OBJECTHANDLE dependentHandle, LoaderAllocator* loaderAllocator) { LIMITED_METHOD_CONTRACT; _dependentHandle = dependentHandle; _loaderAllocator = loaderAllocator; } }; class LAHashKeyToTrackersObject : public Object { #ifdef DACCESS_COMPILE friend class ClrDataAccess; #endif friend class CheckAsmOffsets; friend class CoreLibBinder; public: // _trackerOrTrackerSet is either a reference to a LAHashDependentHashTracker, or to a GCHeapHash of LAHashDependentHashTracker objects. OBJECTREF _trackerOrTrackerSet; // _laLocalKeyValueStore holds an object that represents a Key value (which must always be valid for the lifetime of the // CrossLoaderAllocatorHeapHash, and the values which must also be valid for that entire lifetime. When a value might // have a shorter lifetime it is accessed through the _trackerOrTrackerSet variable, which allows access to hashtables which // are associated with that remote loaderallocator through a dependent handle, so that lifetime can be managed. OBJECTREF _laLocalKeyValueStore; }; typedef DPTR(LAHashDependentHashTrackerObject) PTR_LAHashDependentHashTrackerObject; typedef DPTR(LAHashKeyToTrackersObject) PTR_LAHashKeyToTrackersObject; #ifdef USE_CHECKED_OBJECTREFS typedef REF<LAHashDependentHashTrackerObject> LAHASHDEPENDENTHASHTRACKERREF; typedef REF<LAHashKeyToTrackersObject> LAHASHKEYTOTRACKERSREF; #else // USE_CHECKED_OBJECTREFS typedef PTR_LAHashDependentHashTrackerObject LAHASHDEPENDENTHASHTRACKERREF; typedef PTR_LAHashKeyToTrackersObject LAHASHKEYTOTRACKERSREF; #endif // USE_CHECKED_OBJECTREFS #endif // _OBJECT_H_
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // OBJECT.H // // Definitions of a Com+ Object // // See code:EEStartup#TableOfContents for overview #ifndef _OBJECT_H_ #define _OBJECT_H_ #include "util.hpp" #include "syncblk.h" #include "gcdesc.h" #include "specialstatics.h" #include "sstring.h" #include "daccess.h" #include "fcall.h" extern "C" void __fastcall ZeroMemoryInGCHeap(void*, size_t); void ErectWriteBarrierForMT(MethodTable **dst, MethodTable *ref); /* #ObjectModel * COM+ Internal Object Model * * * Object - This is the common base part to all COM+ objects * | it contains the MethodTable pointer and the * | sync block index, which is at a negative offset * | * +-- code:StringObject - String objects are specialized objects for string * | storage/retrieval for higher performance (UCS-2 / UTF-16 data) * | * +-- code:Utf8StringObject - String objects are specialized objects for string * | storage/retrieval for higher performance (UTF-8 data) * | * +-- BaseObjectWithCachedData - Object Plus one object field for caching. * | | * | +- ReflectClassBaseObject - The base object for the RuntimeType class * | +- ReflectMethodObject - The base object for the RuntimeMethodInfo class * | +- ReflectFieldObject - The base object for the RtFieldInfo class * | * +-- code:ArrayBase - Base portion of all arrays * | | * | +- I1Array - Base type arrays * | | I2Array * | | ... * | | * | +- PtrArray - Array of OBJECTREFs, different than base arrays because of pObjectClass * | * +-- code:AssemblyBaseObject - The base object for the class Assembly * * * PLEASE NOTE THE FOLLOWING WHEN ADDING A NEW OBJECT TYPE: * * The size of the object in the heap must be able to be computed * very, very quickly for GC purposes. Restrictions on the layout * of the object guarantee this is possible. * * Any object that inherits from Object must be able to * compute its complete size by using the first 4 bytes of * the object following the Object part and constants * reachable from the MethodTable... * * The formula used for this calculation is: * MT->GetBaseSize() + ((OBJECTTYPEREF->GetSizeField() * MT->GetComponentSize()) * * So for Object, since this is of fixed size, the ComponentSize is 0, which makes the right side * of the equation above equal to 0 no matter what the value of GetSizeField(), so the size is just the base size. * */ class MethodTable; class Thread; class BaseDomain; class Assembly; class DomainAssembly; class AssemblyNative; class WaitHandleNative; class ArgDestination; struct RCW; #ifdef TARGET_64BIT #define OBJHEADER_SIZE (sizeof(DWORD) /* m_alignpad */ + sizeof(DWORD) /* m_SyncBlockValue */) #else #define OBJHEADER_SIZE sizeof(DWORD) /* m_SyncBlockValue */ #endif #define OBJECT_SIZE TARGET_POINTER_SIZE /* m_pMethTab */ #define OBJECT_BASESIZE (OBJHEADER_SIZE + OBJECT_SIZE) #ifdef TARGET_64BIT #define ARRAYBASE_SIZE (OBJECT_SIZE /* m_pMethTab */ + sizeof(DWORD) /* m_NumComponents */ + sizeof(DWORD) /* pad */) #else #define ARRAYBASE_SIZE (OBJECT_SIZE /* m_pMethTab */ + sizeof(DWORD) /* m_NumComponents */) #endif #define ARRAYBASE_BASESIZE (OBJHEADER_SIZE + ARRAYBASE_SIZE) // // The generational GC requires that every object be at least 12 bytes // in size. #define MIN_OBJECT_SIZE (2*TARGET_POINTER_SIZE + OBJHEADER_SIZE) #define PTRALIGNCONST (DATA_ALIGNMENT-1) #ifndef PtrAlign #define PtrAlign(size) \ (((size) + PTRALIGNCONST) & (~PTRALIGNCONST)) #endif //!PtrAlign // code:Object is the respesentation of an managed object on the GC heap. // // See code:#ObjectModel for some important subclasses of code:Object // // The only fields mandated by all objects are // // * a pointer to the code:MethodTable at offset 0 // * a poiner to a code:ObjHeader at a negative offset. This is often zero. It holds information that // any addition information that we might need to attach to arbitrary objects. // class Object { protected: PTR_MethodTable m_pMethTab; protected: Object() { LIMITED_METHOD_CONTRACT; }; ~Object() { LIMITED_METHOD_CONTRACT; }; public: MethodTable *RawGetMethodTable() const { return m_pMethTab; } #ifndef DACCESS_COMPILE void RawSetMethodTable(MethodTable *pMT) { LIMITED_METHOD_CONTRACT; m_pMethTab = pMT; } VOID SetMethodTable(MethodTable *pMT) { WRAPPER_NO_CONTRACT; RawSetMethodTable(pMT); } VOID SetMethodTableForUOHObject(MethodTable *pMT) { WRAPPER_NO_CONTRACT; // This function must be used if the allocation occurs on a UOH heap, and the method table might be a collectible type ErectWriteBarrierForMT(&m_pMethTab, pMT); } #endif //!DACCESS_COMPILE #define MARKED_BIT 0x1 PTR_MethodTable GetMethodTable() const { LIMITED_METHOD_DAC_CONTRACT; #ifndef DACCESS_COMPILE // We should always use GetGCSafeMethodTable() if we're running during a GC. // If the mark bit is set then we're running during a GC _ASSERTE((dac_cast<TADDR>(m_pMethTab) & MARKED_BIT) == 0); return m_pMethTab; #else //DACCESS_COMPILE //@dbgtodo dharvey Make this a type which supports bitwise and operations //when available return PTR_MethodTable((dac_cast<TADDR>(m_pMethTab)) & (~MARKED_BIT)); #endif //DACCESS_COMPILE } DPTR(PTR_MethodTable) GetMethodTablePtr() const { LIMITED_METHOD_CONTRACT; return dac_cast<DPTR(PTR_MethodTable)>(PTR_HOST_MEMBER_TADDR(Object, this, m_pMethTab)); } TypeHandle GetTypeHandle(); // Methods used to determine if an object supports a given interface. static BOOL SupportsInterface(OBJECTREF pObj, MethodTable *pInterfaceMT); inline DWORD GetNumComponents(); inline SIZE_T GetSize(); CGCDesc* GetSlotMap() { WRAPPER_NO_CONTRACT; return( CGCDesc::GetCGCDescFromMT(GetMethodTable())); } // Sync Block & Synchronization services // Access the ObjHeader which is at a negative offset on the object (because of // cache lines) PTR_ObjHeader GetHeader() { LIMITED_METHOD_DAC_CONTRACT; return dac_cast<PTR_ObjHeader>(this) - 1; } // Get the current address of the object (works for debug refs, too.) PTR_BYTE GetAddress() { LIMITED_METHOD_DAC_CONTRACT; return dac_cast<PTR_BYTE>(this); } #ifdef _DEBUG // TRUE if the header has a real SyncBlockIndex (i.e. it has an entry in the // SyncTable, though it doesn't necessarily have an entry in the SyncBlockCache) BOOL HasEmptySyncBlockInfo() { WRAPPER_NO_CONTRACT; return GetHeader()->HasEmptySyncBlockInfo(); } #endif // retrieve or allocate a sync block for this object SyncBlock *GetSyncBlock() { WRAPPER_NO_CONTRACT; return GetHeader()->GetSyncBlock(); } DWORD GetSyncBlockIndex() { WRAPPER_NO_CONTRACT; return GetHeader()->GetSyncBlockIndex(); } // DO NOT ADD ANY ASSERTS TO THIS METHOD. // DO NOT USE THIS METHOD. // Yes folks, for better or worse the debugger pokes supposed object addresses // to try to see if objects are valid, possibly firing an AccessViolation or worse, // and then catches the AV and reports a failure to the debug client. This makes // the debugger slightly more robust should any corrupted object references appear // in a session. Thus it is "correct" behaviour for this to AV when used with // an invalid object pointer, and incorrect behaviour for it to // assert. BOOL ValidateObjectWithPossibleAV(); // Validate an object ref out of the VerifyHeap routine in the GC void ValidateHeap(BOOL bDeep=TRUE); PTR_SyncBlock PassiveGetSyncBlock() { LIMITED_METHOD_DAC_CONTRACT; return GetHeader()->PassiveGetSyncBlock(); } static DWORD ComputeHashCode(); #ifndef DACCESS_COMPILE INT32 GetHashCodeEx(); #endif // #ifndef DACCESS_COMPILE // Synchronization #ifndef DACCESS_COMPILE void EnterObjMonitor() { WRAPPER_NO_CONTRACT; GetHeader()->EnterObjMonitor(); } BOOL TryEnterObjMonitor(INT32 timeOut = 0) { WRAPPER_NO_CONTRACT; return GetHeader()->TryEnterObjMonitor(timeOut); } bool TryEnterObjMonitorSpinHelper(); FORCEINLINE AwareLock::EnterHelperResult EnterObjMonitorHelper(Thread* pCurThread) { WRAPPER_NO_CONTRACT; return GetHeader()->EnterObjMonitorHelper(pCurThread); } FORCEINLINE AwareLock::EnterHelperResult EnterObjMonitorHelperSpin(Thread* pCurThread) { WRAPPER_NO_CONTRACT; return GetHeader()->EnterObjMonitorHelperSpin(pCurThread); } BOOL LeaveObjMonitor() { WRAPPER_NO_CONTRACT; return GetHeader()->LeaveObjMonitor(); } // should be called only from unwind code; used in the // case where EnterObjMonitor failed to allocate the // sync-object. BOOL LeaveObjMonitorAtException() { WRAPPER_NO_CONTRACT; return GetHeader()->LeaveObjMonitorAtException(); } FORCEINLINE AwareLock::LeaveHelperAction LeaveObjMonitorHelper(Thread* pCurThread) { WRAPPER_NO_CONTRACT; return GetHeader()->LeaveObjMonitorHelper(pCurThread); } // Returns TRUE if the lock is owned and FALSE otherwise // threadId is set to the ID (Thread::GetThreadId()) of the thread which owns the lock // acquisitionCount is set to the number of times the lock needs to be released before // it is unowned BOOL GetThreadOwningMonitorLock(DWORD *pThreadId, DWORD *pAcquisitionCount) { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; return GetHeader()->GetThreadOwningMonitorLock(pThreadId, pAcquisitionCount); } #endif // #ifndef DACCESS_COMPILE BOOL Wait(INT32 timeOut) { WRAPPER_NO_CONTRACT; return GetHeader()->Wait(timeOut); } void Pulse() { WRAPPER_NO_CONTRACT; GetHeader()->Pulse(); } void PulseAll() { WRAPPER_NO_CONTRACT; GetHeader()->PulseAll(); } PTR_VOID UnBox(); // if it is a value class, get the pointer to the first field PTR_BYTE GetData(void) { LIMITED_METHOD_CONTRACT; SUPPORTS_DAC; return dac_cast<PTR_BYTE>(this) + sizeof(Object); } static UINT GetOffsetOfFirstField() { LIMITED_METHOD_CONTRACT; return sizeof(Object); } DWORD GetOffset32(DWORD dwOffset) { WRAPPER_NO_CONTRACT; return * PTR_DWORD(GetData() + dwOffset); } USHORT GetOffset16(DWORD dwOffset) { WRAPPER_NO_CONTRACT; return * PTR_USHORT(GetData() + dwOffset); } BYTE GetOffset8(DWORD dwOffset) { WRAPPER_NO_CONTRACT; return * PTR_BYTE(GetData() + dwOffset); } __int64 GetOffset64(DWORD dwOffset) { WRAPPER_NO_CONTRACT; return (__int64) * PTR_ULONG64(GetData() + dwOffset); } void *GetPtrOffset(DWORD dwOffset) { WRAPPER_NO_CONTRACT; return (void *)(TADDR)*PTR_TADDR(GetData() + dwOffset); } #ifndef DACCESS_COMPILE void SetOffsetObjectRef(DWORD dwOffset, size_t dwValue); void SetOffsetPtr(DWORD dwOffset, LPVOID value) { WRAPPER_NO_CONTRACT; *(LPVOID *) &GetData()[dwOffset] = value; } void SetOffset32(DWORD dwOffset, DWORD dwValue) { WRAPPER_NO_CONTRACT; *(DWORD *) &GetData()[dwOffset] = dwValue; } void SetOffset16(DWORD dwOffset, DWORD dwValue) { WRAPPER_NO_CONTRACT; *(USHORT *) &GetData()[dwOffset] = (USHORT) dwValue; } void SetOffset8(DWORD dwOffset, DWORD dwValue) { WRAPPER_NO_CONTRACT; *(BYTE *) &GetData()[dwOffset] = (BYTE) dwValue; } void SetOffset64(DWORD dwOffset, __int64 qwValue) { WRAPPER_NO_CONTRACT; *(__int64 *) &GetData()[dwOffset] = qwValue; } #endif // #ifndef DACCESS_COMPILE VOID Validate(BOOL bDeep = TRUE, BOOL bVerifyNextHeader = TRUE, BOOL bVerifySyncBlock = TRUE); PTR_MethodTable GetGCSafeMethodTable() const { LIMITED_METHOD_CONTRACT; SUPPORTS_DAC; // lose GC marking bit and the reserved bit // A method table pointer should always be aligned. During GC we set the least // significant bit for marked objects, and the second to least significant // bit is reserved. So if we want the actual MT pointer during a GC // we must zero out the lowest 2 bits on 32-bit and 3 bits on 64-bit. #ifdef TARGET_64BIT return dac_cast<PTR_MethodTable>((dac_cast<TADDR>(m_pMethTab)) & ~((UINT_PTR)7)); #else return dac_cast<PTR_MethodTable>((dac_cast<TADDR>(m_pMethTab)) & ~((UINT_PTR)3)); #endif //TARGET_64BIT } // There are some cases where it is unsafe to get the type handle during a GC. // This occurs when the type has already been unloaded as part of an in-progress appdomain shutdown. TypeHandle GetGCSafeTypeHandleIfPossible() const; inline TypeHandle GetGCSafeTypeHandle() const; #ifdef DACCESS_COMPILE void EnumMemoryRegions(void); #endif private: VOID ValidateInner(BOOL bDeep, BOOL bVerifyNextHeader, BOOL bVerifySyncBlock); }; /* * Object ref setting routines. You must use these to do * proper write barrier support. */ // SetObjectReference sets an OBJECTREF field void SetObjectReferenceUnchecked(OBJECTREF *dst,OBJECTREF ref); #ifdef _DEBUG void EnableStressHeapHelper(); #endif //Used to clear the object reference inline void ClearObjectReference(OBJECTREF* dst) { LIMITED_METHOD_CONTRACT; *(void**)(dst) = NULL; } // CopyValueClass sets a value class field void STDCALL CopyValueClassUnchecked(void* dest, void* src, MethodTable *pMT); void STDCALL CopyValueClassArgUnchecked(ArgDestination *argDest, void* src, MethodTable *pMT, int destOffset); inline void InitValueClass(void *dest, MethodTable *pMT) { WRAPPER_NO_CONTRACT; ZeroMemoryInGCHeap(dest, pMT->GetNumInstanceFieldBytes()); } // Initialize value class argument void InitValueClassArg(ArgDestination *argDest, MethodTable *pMT); #define SetObjectReference(_d,_r) SetObjectReferenceUnchecked(_d, _r) #define CopyValueClass(_d,_s,_m) CopyValueClassUnchecked(_d,_s,_m) #define CopyValueClassArg(_d,_s,_m,_o) CopyValueClassArgUnchecked(_d,_s,_m,_o) #include <pshpack4.h> // There are two basic kinds of array layouts in COM+ // ELEMENT_TYPE_ARRAY - a multidimensional array with lower bounds on the dims // ELMENNT_TYPE_SZARRAY - A zero based single dimensional array // // In addition the layout of an array in memory is also affected by // whether the method table is shared (eg in the case of arrays of object refs) // or not. In the shared case, the array has to hold the type handle of // the element type. // // ArrayBase encapuslates all of these details. In theory you should never // have to peek inside this abstraction // class ArrayBase : public Object { friend class GCHeap; friend class CObjectHeader; friend class Object; friend OBJECTREF AllocateSzArray(MethodTable *pArrayMT, INT32 length, GC_ALLOC_FLAGS flags); friend OBJECTREF AllocateArrayEx(MethodTable *pArrayMT, INT32 *pArgs, DWORD dwNumArgs, GC_ALLOC_FLAGS flags); friend FCDECL2(Object*, JIT_NewArr1VC_MP_FastPortable, CORINFO_CLASS_HANDLE arrayMT, INT_PTR size); friend FCDECL2(Object*, JIT_NewArr1OBJ_MP_FastPortable, CORINFO_CLASS_HANDLE arrayMT, INT_PTR size); friend class JIT_TrialAlloc; friend class CheckAsmOffsets; friend struct _DacGlobals; private: // This MUST be the first field, so that it directly follows Object. This is because // Object::GetSize() looks at m_NumComponents even though it may not be an array (the // values is shifted out if not an array, so it's ok). DWORD m_NumComponents; #ifdef TARGET_64BIT DWORD pad; #endif // TARGET_64BIT SVAL_DECL(INT32, s_arrayBoundsZero); // = 0 // What comes after this conceputally is: // INT32 bounds[rank]; The bounds are only present for Multidimensional arrays // INT32 lowerBounds[rank]; Valid indexes are lowerBounds[i] <= index[i] < lowerBounds[i] + bounds[i] public: // Get the element type for the array, this works whether the the element // type is stored in the array or not inline TypeHandle GetArrayElementTypeHandle() const; // Get the CorElementType for the elements in the array. Avoids creating a TypeHandle inline CorElementType GetArrayElementType() const; inline unsigned GetRank() const; // Total element count for the array inline DWORD GetNumComponents() const; // Get pointer to elements, handles any number of dimensions PTR_BYTE GetDataPtr(BOOL inGC = FALSE) const { LIMITED_METHOD_CONTRACT; SUPPORTS_DAC; #ifdef _DEBUG #ifndef DACCESS_COMPILE EnableStressHeapHelper(); #endif #endif return dac_cast<PTR_BYTE>(this) + GetDataPtrOffset(inGC ? GetGCSafeMethodTable() : GetMethodTable()); } // The component size is actually 16-bit WORD, but this method is returning SIZE_T to ensure // that SIZE_T is used everywhere for object size computation. It is necessary to support // objects bigger than 2GB. SIZE_T GetComponentSize() const { WRAPPER_NO_CONTRACT; MethodTable * pMT; pMT = GetMethodTable(); _ASSERTE(pMT->HasComponentSize()); return pMT->RawGetComponentSize(); } // Note that this can be a multidimensional array of rank 1 // (for example if we had a 1-D array with lower bounds BOOL IsMultiDimArray() const { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; return(GetMethodTable()->IsMultiDimArray()); } // Get pointer to the beginning of the bounds (counts for each dim) // Works for any array type PTR_INT32 GetBoundsPtr() const { WRAPPER_NO_CONTRACT; MethodTable * pMT = GetMethodTable(); if (pMT->IsMultiDimArray()) { return dac_cast<PTR_INT32>( dac_cast<TADDR>(this) + sizeof(*this)); } else { return dac_cast<PTR_INT32>(PTR_HOST_MEMBER_TADDR(ArrayBase, this, m_NumComponents)); } } // Works for any array type PTR_INT32 GetLowerBoundsPtr() const { WRAPPER_NO_CONTRACT; if (IsMultiDimArray()) { // Lower bounds info is after total bounds info // and total bounds info has rank elements return GetBoundsPtr() + GetRank(); } else return dac_cast<PTR_INT32>(GVAL_ADDR(s_arrayBoundsZero)); } static unsigned GetOffsetOfNumComponents() { LIMITED_METHOD_CONTRACT; return offsetof(ArrayBase, m_NumComponents); } inline static unsigned GetDataPtrOffset(MethodTable* pMT); inline static unsigned GetBoundsOffset(MethodTable* pMT); inline static unsigned GetLowerBoundsOffset(MethodTable* pMT); }; // // Template used to build all the non-object // arrays of a single dimension // template < class KIND > class Array : public ArrayBase { public: typedef DPTR(KIND) PTR_KIND; typedef DPTR(const KIND) PTR_CKIND; KIND m_Array[1]; PTR_KIND GetDirectPointerToNonObjectElements() { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; // return m_Array; return PTR_KIND(GetDataPtr()); // This also handles arrays of dim 1 with lower bounds present } PTR_CKIND GetDirectConstPointerToNonObjectElements() const { WRAPPER_NO_CONTRACT; // return m_Array; return PTR_CKIND(GetDataPtr()); // This also handles arrays of dim 1 with lower bounds present } }; // Warning: Use PtrArray only for single dimensional arrays, not multidim arrays. class PtrArray : public ArrayBase { friend class GCHeap; friend class ClrDataAccess; friend OBJECTREF AllocateArrayEx(MethodTable *pArrayMT, INT32 *pArgs, DWORD dwNumArgs, DWORD flags); friend class JIT_TrialAlloc; friend class CheckAsmOffsets; public: TypeHandle GetArrayElementTypeHandle() { LIMITED_METHOD_CONTRACT; return GetMethodTable()->GetArrayElementTypeHandle(); } PTR_OBJECTREF GetDataPtr() { LIMITED_METHOD_CONTRACT; SUPPORTS_DAC; return dac_cast<PTR_OBJECTREF>(dac_cast<PTR_BYTE>(this) + GetDataOffset()); } static SIZE_T GetDataOffset() { LIMITED_METHOD_CONTRACT; return offsetof(PtrArray, m_Array); } void SetAt(SIZE_T i, OBJECTREF ref) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; _ASSERTE(i < GetNumComponents()); SetObjectReference(m_Array + i, ref); } void ClearAt(SIZE_T i) { WRAPPER_NO_CONTRACT; _ASSERTE(i < GetNumComponents()); ClearObjectReference(m_Array + i); } OBJECTREF GetAt(SIZE_T i) { LIMITED_METHOD_CONTRACT; SUPPORTS_DAC; _ASSERTE(i < GetNumComponents()); // DAC doesn't know the true size of this array // the compiler thinks it is size 1, but really it is size N hanging off the structure #ifndef DACCESS_COMPILE return m_Array[i]; #else TADDR arrayTargetAddress = dac_cast<TADDR>(this) + offsetof(PtrArray, m_Array); __ArrayDPtr<OBJECTREF> targetArray = dac_cast< __ArrayDPtr<OBJECTREF> >(arrayTargetAddress); return targetArray[i]; #endif } friend class StubLinkerCPU; #ifdef FEATURE_ARRAYSTUB_AS_IL friend class ArrayOpLinker; #endif public: OBJECTREF m_Array[1]; }; #define OFFSETOF__PtrArray__m_Array_ ARRAYBASE_SIZE /* Corresponds to the managed Span<T> and ReadOnlySpan<T> types. This should only ever be passed from the managed to the unmanaged world byref, as any copies of this struct made within the unmanaged world will not observe potential GC relocations of the source data. */ template < class KIND > class Span { private: /* Keep fields below in sync with managed Span / ReadOnlySpan layout. */ KIND* _pointer; unsigned int _length; public: // !! CAUTION !! // Caller must take care not to reassign returned reference if this span corresponds // to a managed ReadOnlySpan<T>. If KIND is a reference type, caller must use a // helper like SetObjectReference instead of assigning values directly to the // reference location. KIND& GetAt(SIZE_T index) { LIMITED_METHOD_CONTRACT; SUPPORTS_DAC; _ASSERTE(index < GetLength()); return _pointer[index]; } // Gets the length (in elements) of this span. __inline SIZE_T GetLength() const { return _length; } }; /* a TypedByRef is a structure that is used to implement VB's BYREF variants. it is basically a tuple of an address of some data along with a TypeHandle that indicates the type of the address */ class TypedByRef { public: PTR_VOID data; TypeHandle type; }; typedef DPTR(TypedByRef) PTR_TypedByRef; typedef Array<I1> I1Array; typedef Array<I2> I2Array; typedef Array<I4> I4Array; typedef Array<I8> I8Array; typedef Array<R4> R4Array; typedef Array<R8> R8Array; typedef Array<U1> U1Array; typedef Array<U1> BOOLArray; typedef Array<U2> U2Array; typedef Array<WCHAR> CHARArray; typedef Array<U4> U4Array; typedef Array<U8> U8Array; typedef Array<UPTR> UPTRArray; typedef PtrArray PTRArray; typedef DPTR(I1Array) PTR_I1Array; typedef DPTR(I2Array) PTR_I2Array; typedef DPTR(I4Array) PTR_I4Array; typedef DPTR(I8Array) PTR_I8Array; typedef DPTR(R4Array) PTR_R4Array; typedef DPTR(R8Array) PTR_R8Array; typedef DPTR(U1Array) PTR_U1Array; typedef DPTR(BOOLArray) PTR_BOOLArray; typedef DPTR(U2Array) PTR_U2Array; typedef DPTR(CHARArray) PTR_CHARArray; typedef DPTR(U4Array) PTR_U4Array; typedef DPTR(U8Array) PTR_U8Array; typedef DPTR(UPTRArray) PTR_UPTRArray; typedef DPTR(PTRArray) PTR_PTRArray; class StringObject; #ifdef USE_CHECKED_OBJECTREFS typedef REF<ArrayBase> BASEARRAYREF; typedef REF<I1Array> I1ARRAYREF; typedef REF<I2Array> I2ARRAYREF; typedef REF<I4Array> I4ARRAYREF; typedef REF<I8Array> I8ARRAYREF; typedef REF<R4Array> R4ARRAYREF; typedef REF<R8Array> R8ARRAYREF; typedef REF<U1Array> U1ARRAYREF; typedef REF<BOOLArray> BOOLARRAYREF; typedef REF<U2Array> U2ARRAYREF; typedef REF<U4Array> U4ARRAYREF; typedef REF<U8Array> U8ARRAYREF; typedef REF<UPTRArray> UPTRARRAYREF; typedef REF<CHARArray> CHARARRAYREF; typedef REF<PTRArray> PTRARRAYREF; // Warning: Use PtrArray only for single dimensional arrays, not multidim arrays. typedef REF<StringObject> STRINGREF; #else // USE_CHECKED_OBJECTREFS typedef PTR_ArrayBase BASEARRAYREF; typedef PTR_I1Array I1ARRAYREF; typedef PTR_I2Array I2ARRAYREF; typedef PTR_I4Array I4ARRAYREF; typedef PTR_I8Array I8ARRAYREF; typedef PTR_R4Array R4ARRAYREF; typedef PTR_R8Array R8ARRAYREF; typedef PTR_U1Array U1ARRAYREF; typedef PTR_BOOLArray BOOLARRAYREF; typedef PTR_U2Array U2ARRAYREF; typedef PTR_U4Array U4ARRAYREF; typedef PTR_U8Array U8ARRAYREF; typedef PTR_UPTRArray UPTRARRAYREF; typedef PTR_CHARArray CHARARRAYREF; typedef PTR_PTRArray PTRARRAYREF; // Warning: Use PtrArray only for single dimensional arrays, not multidim arrays. typedef PTR_StringObject STRINGREF; #endif // USE_CHECKED_OBJECTREFS #include <poppack.h> /* * StringObject * * Special String implementation for performance. * * m_StringLength - Length of string in number of WCHARs * m_FirstChar - The string buffer * */ class StringObject : public Object { #ifdef DACCESS_COMPILE friend class ClrDataAccess; #endif friend class GCHeap; friend class JIT_TrialAlloc; friend class CheckAsmOffsets; friend class COMString; private: DWORD m_StringLength; WCHAR m_FirstChar; public: VOID SetStringLength(DWORD len) { LIMITED_METHOD_CONTRACT; _ASSERTE(len >= 0); m_StringLength = len; } protected: StringObject() {LIMITED_METHOD_CONTRACT; } ~StringObject() {LIMITED_METHOD_CONTRACT; } public: static DWORD GetBaseSize(); static SIZE_T GetSize(DWORD stringLength); DWORD GetStringLength() { LIMITED_METHOD_DAC_CONTRACT; return( m_StringLength );} WCHAR* GetBuffer() { LIMITED_METHOD_CONTRACT; return (WCHAR*)( dac_cast<TADDR>(this) + offsetof(StringObject, m_FirstChar) ); } static UINT GetBufferOffset() { LIMITED_METHOD_DAC_CONTRACT; return (UINT)(offsetof(StringObject, m_FirstChar)); } static UINT GetStringLengthOffset() { LIMITED_METHOD_CONTRACT; return (UINT)(offsetof(StringObject, m_StringLength)); } VOID GetSString(SString &result) { WRAPPER_NO_CONTRACT; result.Set(GetBuffer(), GetStringLength()); } //======================================================================== // Creates a System.String object. All the functions that take a length // or a count of bytes will add the null terminator after length // characters. So this means that if you have a string that has 5 // characters and the null terminator you should pass in 5 and NOT 6. //======================================================================== static STRINGREF NewString(int length); static STRINGREF NewString(int length, BOOL bHasTrailByte); static STRINGREF NewString(const WCHAR *pwsz); static STRINGREF NewString(const WCHAR *pwsz, int length); static STRINGREF NewString(LPCUTF8 psz); static STRINGREF NewString(LPCUTF8 psz, int cBytes); static STRINGREF GetEmptyString(); static STRINGREF* GetEmptyStringRefPtr(); static STRINGREF* InitEmptyStringRefPtr(); BOOL HasTrailByte(); BOOL GetTrailByte(BYTE *bTrailByte); BOOL SetTrailByte(BYTE bTrailByte); static BOOL CaseInsensitiveCompHelper(_In_reads_(aLength) WCHAR * strA, _In_z_ INT8 * strB, int aLength, int bLength, int *result); /*=================RefInterpretGetStringValuesDangerousForGC====================== **N.B.: This perfoms no range checking and relies on the caller to have done this. **Args: (IN)ref -- the String to be interpretted. ** (OUT)chars -- a pointer to the characters in the buffer. ** (OUT)length -- a pointer to the length of the buffer. **Returns: void. **Exceptions: None. ==============================================================================*/ // !!!! If you use this function, you have to be careful because chars is a pointer // !!!! to the data buffer of ref. If GC happens after this call, you need to make // !!!! sure that you have a pin handle on ref, or use GCPROTECT_BEGINPINNING on ref. void RefInterpretGetStringValuesDangerousForGC(_Outptr_result_buffer_(*length + 1) WCHAR **chars, int *length) { WRAPPER_NO_CONTRACT; _ASSERTE(GetGCSafeMethodTable() == g_pStringClass); *length = GetStringLength(); *chars = GetBuffer(); #ifdef _DEBUG EnableStressHeapHelper(); #endif } private: static STRINGREF* EmptyStringRefPtr; }; /*================================GetEmptyString================================ **Get a reference to the empty string. If we haven't already gotten one, we **query the String class for a pointer to the empty string that we know was **created at startup. ** **Args: None **Returns: A STRINGREF to the EmptyString **Exceptions: None ==============================================================================*/ inline STRINGREF StringObject::GetEmptyString() { CONTRACTL { THROWS; MODE_COOPERATIVE; GC_TRIGGERS; } CONTRACTL_END; STRINGREF* refptr = EmptyStringRefPtr; //If we've never gotten a reference to the EmptyString, we need to go get one. if (refptr==NULL) { refptr = InitEmptyStringRefPtr(); } //We've already have a reference to the EmptyString, so we can just return it. return *refptr; } inline STRINGREF* StringObject::GetEmptyStringRefPtr() { CONTRACTL { THROWS; MODE_ANY; GC_TRIGGERS; } CONTRACTL_END; STRINGREF* refptr = EmptyStringRefPtr; //If we've never gotten a reference to the EmptyString, we need to go get one. if (refptr==NULL) { refptr = InitEmptyStringRefPtr(); } //We've already have a reference to the EmptyString, so we can just return it. return refptr; } // This is used to account for the remoting cache on RuntimeType, // RuntimeMethodInfo, and RtFieldInfo. class BaseObjectWithCachedData : public Object { }; // This is the Class version of the Reflection object. // A Class has adddition information. // For a ReflectClassBaseObject the m_pData is a pointer to a FieldDesc array that // contains all of the final static primitives if its defined. // m_cnt = the number of elements defined in the m_pData FieldDesc array. -1 means // this hasn't yet been defined. class ReflectClassBaseObject : public BaseObjectWithCachedData { friend class CoreLibBinder; protected: OBJECTREF m_keepalive; OBJECTREF m_cache; TypeHandle m_typeHandle; #ifdef _DEBUG void TypeCheck() { CONTRACTL { NOTHROW; MODE_COOPERATIVE; GC_NOTRIGGER; } CONTRACTL_END; MethodTable *pMT = GetMethodTable(); while (pMT != g_pRuntimeTypeClass && pMT != NULL) { pMT = pMT->GetParentMethodTable(); } _ASSERTE(pMT == g_pRuntimeTypeClass); } #endif // _DEBUG public: void SetType(TypeHandle type) { CONTRACTL { NOTHROW; MODE_COOPERATIVE; GC_NOTRIGGER; } CONTRACTL_END; INDEBUG(TypeCheck()); m_typeHandle = type; } void SetKeepAlive(OBJECTREF keepalive) { CONTRACTL { NOTHROW; MODE_COOPERATIVE; GC_NOTRIGGER; } CONTRACTL_END; INDEBUG(TypeCheck()); SetObjectReference(&m_keepalive, keepalive); } TypeHandle GetType() { CONTRACTL { NOTHROW; MODE_COOPERATIVE; GC_NOTRIGGER; } CONTRACTL_END; INDEBUG(TypeCheck()); return m_typeHandle; } }; // This is the Method version of the Reflection object. // A Method has adddition information. // m_pMD - A pointer to the actual MethodDesc of the method. // m_object - a field that has a reference type in it. Used only for RuntimeMethodInfoStub to keep the real type alive. // This structure matches the structure up to the m_pMD for several different managed types. // (RuntimeConstructorInfo, RuntimeMethodInfo, and RuntimeMethodInfoStub). These types are unrelated in the type // system except that they all implement a particular interface. It is important that that interface is not attached to any // type that does not sufficiently match this data structure. class ReflectMethodObject : public BaseObjectWithCachedData { friend class CoreLibBinder; protected: OBJECTREF m_object; OBJECTREF m_empty1; OBJECTREF m_empty2; OBJECTREF m_empty3; OBJECTREF m_empty4; OBJECTREF m_empty5; OBJECTREF m_empty6; OBJECTREF m_empty7; MethodDesc * m_pMD; public: void SetMethod(MethodDesc *pMethod) { LIMITED_METHOD_CONTRACT; m_pMD = pMethod; } // This must only be called on instances of ReflectMethodObject that are actually RuntimeMethodInfoStub void SetKeepAlive(OBJECTREF keepalive) { WRAPPER_NO_CONTRACT; SetObjectReference(&m_object, keepalive); } MethodDesc *GetMethod() { LIMITED_METHOD_CONTRACT; return m_pMD; } }; // This is the Field version of the Reflection object. // A Method has adddition information. // m_pFD - A pointer to the actual MethodDesc of the method. // m_object - a field that has a reference type in it. Used only for RuntimeFieldInfoStub to keep the real type alive. // This structure matches the structure up to the m_pFD for several different managed types. // (RtFieldInfo and RuntimeFieldInfoStub). These types are unrelated in the type // system except that they all implement a particular interface. It is important that that interface is not attached to any // type that does not sufficiently match this data structure. class ReflectFieldObject : public BaseObjectWithCachedData { friend class CoreLibBinder; protected: OBJECTREF m_object; OBJECTREF m_empty1; INT32 m_empty2; OBJECTREF m_empty3; OBJECTREF m_empty4; FieldDesc * m_pFD; public: void SetField(FieldDesc *pField) { LIMITED_METHOD_CONTRACT; m_pFD = pField; } // This must only be called on instances of ReflectFieldObject that are actually RuntimeFieldInfoStub void SetKeepAlive(OBJECTREF keepalive) { WRAPPER_NO_CONTRACT; SetObjectReference(&m_object, keepalive); } FieldDesc *GetField() { LIMITED_METHOD_CONTRACT; return m_pFD; } }; // ReflectModuleBaseObject // This class is the base class for managed Module. // This class will connect the Object back to the underlying VM representation // m_ReflectClass -- This is the real Class that was used for reflection // This class was used to get at this object // m_pData -- this is a generic pointer which usually points CorModule // class ReflectModuleBaseObject : public Object { friend class CoreLibBinder; protected: // READ ME: // Modifying the order or fields of this object may require other changes to the // classlib class definition of this object. OBJECTREF m_runtimeType; OBJECTREF m_runtimeAssembly; void* m_ReflectClass; // Pointer to the ReflectClass structure Module* m_pData; // Pointer to the Module void* m_pGlobals; // Global values.... void* m_pGlobalsFlds; // Global Fields.... protected: ReflectModuleBaseObject() {LIMITED_METHOD_CONTRACT;} ~ReflectModuleBaseObject() {LIMITED_METHOD_CONTRACT;} public: void SetModule(Module* p) { LIMITED_METHOD_CONTRACT; m_pData = p; } Module* GetModule() { LIMITED_METHOD_CONTRACT; return m_pData; } void SetAssembly(OBJECTREF assembly) { WRAPPER_NO_CONTRACT; SetObjectReference(&m_runtimeAssembly, assembly); } }; NOINLINE ReflectModuleBaseObject* GetRuntimeModuleHelper(LPVOID __me, Module *pModule, OBJECTREF keepAlive); #define FC_RETURN_MODULE_OBJECT(pModule, refKeepAlive) FC_INNER_RETURN(ReflectModuleBaseObject*, GetRuntimeModuleHelper(__me, pModule, refKeepAlive)) class SafeHandle; #ifdef USE_CHECKED_OBJECTREFS typedef REF<SafeHandle> SAFEHANDLE; typedef REF<SafeHandle> SAFEHANDLEREF; #else // USE_CHECKED_OBJECTREFS typedef SafeHandle * SAFEHANDLE; typedef SafeHandle * SAFEHANDLEREF; #endif // USE_CHECKED_OBJECTREFS class ThreadBaseObject; class SynchronizationContextObject: public Object { friend class CoreLibBinder; private: // These field are also defined in the managed representation. (SecurityContext.cs)If you // add or change these field you must also change the managed code so that // it matches these. This is necessary so that the object is the proper // size. CLR_BOOL _requireWaitNotification; public: BOOL IsWaitNotificationRequired() const { LIMITED_METHOD_CONTRACT; return _requireWaitNotification; } }; typedef DPTR(class CultureInfoBaseObject) PTR_CultureInfoBaseObject; #ifdef USE_CHECKED_OBJECTREFS typedef REF<SynchronizationContextObject> SYNCHRONIZATIONCONTEXTREF; typedef REF<ExecutionContextObject> EXECUTIONCONTEXTREF; typedef REF<CultureInfoBaseObject> CULTUREINFOBASEREF; typedef REF<ArrayBase> ARRAYBASEREF; #else typedef SynchronizationContextObject* SYNCHRONIZATIONCONTEXTREF; typedef CultureInfoBaseObject* CULTUREINFOBASEREF; typedef PTR_ArrayBase ARRAYBASEREF; #endif // Note that the name must always be "" or "en-US". Other cases and nulls // aren't allowed (we already checked.) __inline bool IsCultureEnglishOrInvariant(LPCWSTR localeName) { LIMITED_METHOD_CONTRACT; if (localeName != NULL && (localeName[0] == W('\0') || wcscmp(localeName, W("en-US")) == 0)) { return true; } return false; } class CultureInfoBaseObject : public Object { friend class CoreLibBinder; private: OBJECTREF _compareInfo; OBJECTREF _textInfo; OBJECTREF _numInfo; OBJECTREF _dateTimeInfo; OBJECTREF _calendar; OBJECTREF _cultureData; OBJECTREF _consoleFallbackCulture; STRINGREF _name; // "real" name - en-US, de-DE_phoneb or fj-FJ STRINGREF _nonSortName; // name w/o sort info (de-DE for de-DE_phoneb) STRINGREF _sortName; // Sort only name (de-DE_phoneb, en-us for fj-fj (w/us sort) CULTUREINFOBASEREF _parent; CLR_BOOL _isReadOnly; CLR_BOOL _isInherited; public: CULTUREINFOBASEREF GetParent() { LIMITED_METHOD_CONTRACT; return _parent; }// GetParent STRINGREF GetName() { LIMITED_METHOD_CONTRACT; return _name; }// GetName }; // class CultureInfoBaseObject typedef DPTR(class ThreadBaseObject) PTR_ThreadBaseObject; class ThreadBaseObject : public Object { friend class ClrDataAccess; friend class ThreadNative; friend class CoreLibBinder; friend class Object; private: // These field are also defined in the managed representation. If you // add or change these field you must also change the managed code so that // it matches these. This is necessary so that the object is the proper // size. The order here must match that order which the loader will choose // when laying out the managed class. Note that the layouts are checked // at run time, not compile time. OBJECTREF m_ExecutionContext; OBJECTREF m_SynchronizationContext; STRINGREF m_Name; OBJECTREF m_StartHelper; // The next field (m_InternalThread) is declared as IntPtr in the managed // definition of Thread. The loader will sort it next. // m_InternalThread is always valid -- unless the thread has finalized and been // resurrected. (The thread stopped running before it was finalized). Thread *m_InternalThread; INT32 m_Priority; // We need to cache the thread id in managed code for perf reasons. INT32 m_ManagedThreadId; // Only used by managed code, see comment there bool m_MayNeedResetForThreadPool; protected: // the ctor and dtor can do no useful work. ThreadBaseObject() {LIMITED_METHOD_CONTRACT;}; ~ThreadBaseObject() {LIMITED_METHOD_CONTRACT;}; public: Thread *GetInternal() { LIMITED_METHOD_CONTRACT; return m_InternalThread; } void SetInternal(Thread *it); void ClearInternal(); INT32 GetManagedThreadId() { LIMITED_METHOD_CONTRACT; return m_ManagedThreadId; } void SetManagedThreadId(INT32 id) { LIMITED_METHOD_CONTRACT; m_ManagedThreadId = id; } STRINGREF GetName() { LIMITED_METHOD_CONTRACT; return m_Name; } OBJECTREF GetSynchronizationContext() { LIMITED_METHOD_CONTRACT; return m_SynchronizationContext; } void InitExisting(); void ResetStartHelper() { LIMITED_METHOD_CONTRACT m_StartHelper = NULL; } void ResetName() { LIMITED_METHOD_CONTRACT; m_Name = NULL; } void SetPriority(INT32 priority) { LIMITED_METHOD_CONTRACT; m_Priority = priority; } INT32 GetPriority() const { LIMITED_METHOD_CONTRACT; return m_Priority; } }; // MarshalByRefObjectBaseObject // This class is the base class for MarshalByRefObject // class MarshalByRefObjectBaseObject : public Object { }; // AssemblyBaseObject // This class is the base class for assemblies // class AssemblyBaseObject : public Object { friend class Assembly; friend class CoreLibBinder; protected: // READ ME: // Modifying the order or fields of this object may require other changes to the // classlib class definition of this object. OBJECTREF m_pModuleEventHandler; // Delegate for 'resolve module' event STRINGREF m_fullname; // Slot for storing assemblies fullname OBJECTREF m_pSyncRoot; // Pointer to loader allocator to keep collectible types alive, and to serve as the syncroot for assembly building in ref.emit DomainAssembly* m_pAssembly; // Pointer to the Assembly Structure protected: AssemblyBaseObject() { LIMITED_METHOD_CONTRACT; } ~AssemblyBaseObject() { LIMITED_METHOD_CONTRACT; } public: void SetAssembly(DomainAssembly* p) { LIMITED_METHOD_CONTRACT; m_pAssembly = p; } DomainAssembly* GetDomainAssembly() { LIMITED_METHOD_CONTRACT; return m_pAssembly; } Assembly* GetAssembly(); void SetSyncRoot(OBJECTREF pSyncRoot) { WRAPPER_NO_CONTRACT; SetObjectReference(&m_pSyncRoot, pSyncRoot); } }; NOINLINE AssemblyBaseObject* GetRuntimeAssemblyHelper(LPVOID __me, DomainAssembly *pAssembly, OBJECTREF keepAlive); #define FC_RETURN_ASSEMBLY_OBJECT(pAssembly, refKeepAlive) FC_INNER_RETURN(AssemblyBaseObject*, GetRuntimeAssemblyHelper(__me, pAssembly, refKeepAlive)) // AssemblyLoadContextBaseObject // This class is the base class for AssemblyLoadContext // #if defined(TARGET_X86) && !defined(TARGET_UNIX) #include "pshpack4.h" #endif // defined(TARGET_X86) && !defined(TARGET_UNIX) class AssemblyLoadContextBaseObject : public Object { friend class CoreLibBinder; protected: // READ ME: // Modifying the order or fields of this object may require other changes to the // classlib class definition of this object. #ifdef TARGET_64BIT OBJECTREF _unloadLock; OBJECTREF _resovlingUnmanagedDll; OBJECTREF _resolving; OBJECTREF _unloading; OBJECTREF _name; INT_PTR _nativeAssemblyLoadContext; int64_t _id; // On 64-bit platforms this is a value type so it is placed after references and pointers DWORD _state; CLR_BOOL _isCollectible; #else // TARGET_64BIT int64_t _id; // On 32-bit platforms this 64-bit value type is larger than a pointer so JIT places it first OBJECTREF _unloadLock; OBJECTREF _resovlingUnmanagedDll; OBJECTREF _resolving; OBJECTREF _unloading; OBJECTREF _name; INT_PTR _nativeAssemblyLoadContext; DWORD _state; CLR_BOOL _isCollectible; #endif // TARGET_64BIT protected: AssemblyLoadContextBaseObject() { LIMITED_METHOD_CONTRACT; } ~AssemblyLoadContextBaseObject() { LIMITED_METHOD_CONTRACT; } public: INT_PTR GetNativeAssemblyBinder() { LIMITED_METHOD_CONTRACT; return _nativeAssemblyLoadContext; } }; #if defined(TARGET_X86) && !defined(TARGET_UNIX) #include "poppack.h" #endif // defined(TARGET_X86) && !defined(TARGET_UNIX) // AssemblyNameBaseObject // This class is the base class for assembly names // class AssemblyNameBaseObject : public Object { friend class AssemblyNative; friend class AppDomainNative; friend class CoreLibBinder; protected: // READ ME: // Modifying the order or fields of this object may require other changes to the // classlib class definition of this object. OBJECTREF _name; U1ARRAYREF _publicKey; U1ARRAYREF _publicKeyToken; OBJECTREF _cultureInfo; OBJECTREF _codeBase; OBJECTREF _version; DWORD _hashAlgorithm; DWORD _versionCompatibility; DWORD _flags; protected: AssemblyNameBaseObject() { LIMITED_METHOD_CONTRACT; } ~AssemblyNameBaseObject() { LIMITED_METHOD_CONTRACT; } public: OBJECTREF GetSimpleName() { LIMITED_METHOD_CONTRACT; return _name; } U1ARRAYREF GetPublicKey() { LIMITED_METHOD_CONTRACT; return _publicKey; } U1ARRAYREF GetPublicKeyToken() { LIMITED_METHOD_CONTRACT; return _publicKeyToken; } OBJECTREF GetCultureInfo() { LIMITED_METHOD_CONTRACT; return _cultureInfo; } OBJECTREF GetAssemblyCodeBase() { LIMITED_METHOD_CONTRACT; return _codeBase; } OBJECTREF GetVersion() { LIMITED_METHOD_CONTRACT; return _version; } DWORD GetAssemblyHashAlgorithm() { LIMITED_METHOD_CONTRACT; return _hashAlgorithm; } DWORD GetFlags() { LIMITED_METHOD_CONTRACT; return _flags; } }; // VersionBaseObject // This class is the base class for versions // class VersionBaseObject : public Object { friend class CoreLibBinder; protected: // READ ME: // Modifying the order or fields of this object may require other changes to the // classlib class definition of this object. int m_Major; int m_Minor; int m_Build; int m_Revision; VersionBaseObject() {LIMITED_METHOD_CONTRACT;} ~VersionBaseObject() {LIMITED_METHOD_CONTRACT;} public: int GetMajor() { LIMITED_METHOD_CONTRACT; return m_Major; } int GetMinor() { LIMITED_METHOD_CONTRACT; return m_Minor; } int GetBuild() { LIMITED_METHOD_CONTRACT; return m_Build; } int GetRevision() { LIMITED_METHOD_CONTRACT; return m_Revision; } }; class WeakReferenceObject : public Object { public: Volatile<OBJECTHANDLE> m_Handle; }; #ifdef USE_CHECKED_OBJECTREFS typedef REF<ReflectModuleBaseObject> REFLECTMODULEBASEREF; typedef REF<ReflectClassBaseObject> REFLECTCLASSBASEREF; typedef REF<ReflectMethodObject> REFLECTMETHODREF; typedef REF<ReflectFieldObject> REFLECTFIELDREF; typedef REF<ThreadBaseObject> THREADBASEREF; typedef REF<MarshalByRefObjectBaseObject> MARSHALBYREFOBJECTBASEREF; typedef REF<AssemblyBaseObject> ASSEMBLYREF; typedef REF<AssemblyLoadContextBaseObject> ASSEMBLYLOADCONTEXTREF; typedef REF<AssemblyNameBaseObject> ASSEMBLYNAMEREF; typedef REF<VersionBaseObject> VERSIONREF; typedef REF<WeakReferenceObject> WEAKREFERENCEREF; inline ARG_SLOT ObjToArgSlot(OBJECTREF objRef) { LIMITED_METHOD_CONTRACT; LPVOID v; v = OBJECTREFToObject(objRef); return (ARG_SLOT)(SIZE_T)v; } inline OBJECTREF ArgSlotToObj(ARG_SLOT i) { LIMITED_METHOD_CONTRACT; LPVOID v; v = (LPVOID)(SIZE_T)i; return ObjectToOBJECTREF ((Object*)v); } inline ARG_SLOT StringToArgSlot(STRINGREF sr) { LIMITED_METHOD_CONTRACT; LPVOID v; v = OBJECTREFToObject(sr); return (ARG_SLOT)(SIZE_T)v; } inline STRINGREF ArgSlotToString(ARG_SLOT s) { LIMITED_METHOD_CONTRACT; LPVOID v; v = (LPVOID)(SIZE_T)s; return ObjectToSTRINGREF ((StringObject*)v); } #else // USE_CHECKED_OBJECTREFS typedef PTR_ReflectModuleBaseObject REFLECTMODULEBASEREF; typedef PTR_ReflectClassBaseObject REFLECTCLASSBASEREF; typedef PTR_ReflectMethodObject REFLECTMETHODREF; typedef PTR_ReflectFieldObject REFLECTFIELDREF; typedef PTR_ThreadBaseObject THREADBASEREF; typedef PTR_AssemblyBaseObject ASSEMBLYREF; typedef PTR_AssemblyLoadContextBaseObject ASSEMBLYLOADCONTEXTREF; typedef PTR_AssemblyNameBaseObject ASSEMBLYNAMEREF; #ifndef DACCESS_COMPILE typedef MarshalByRefObjectBaseObject* MARSHALBYREFOBJECTBASEREF; typedef VersionBaseObject* VERSIONREF; typedef WeakReferenceObject* WEAKREFERENCEREF; #endif // #ifndef DACCESS_COMPILE #define ObjToArgSlot(objref) ((ARG_SLOT)(SIZE_T)(objref)) #define ArgSlotToObj(s) ((OBJECTREF)(SIZE_T)(s)) #define StringToArgSlot(objref) ((ARG_SLOT)(SIZE_T)(objref)) #define ArgSlotToString(s) ((STRINGREF)(SIZE_T)(s)) #endif //USE_CHECKED_OBJECTREFS #define PtrToArgSlot(ptr) ((ARG_SLOT)(SIZE_T)(ptr)) #define ArgSlotToPtr(s) ((LPVOID)(SIZE_T)(s)) #define BoolToArgSlot(b) ((ARG_SLOT)(CLR_BOOL)(!!(b))) #define ArgSlotToBool(s) ((BOOL)(s)) STRINGREF AllocateString(SString sstr); CHARARRAYREF AllocateCharArray(DWORD dwArrayLength); #ifdef FEATURE_COMINTEROP //------------------------------------------------------------- // class ComObject, Exposed class __ComObject // // //------------------------------------------------------------- class ComObject : public MarshalByRefObjectBaseObject { friend class CoreLibBinder; protected: ComObject() {LIMITED_METHOD_CONTRACT;}; // don't instantiate this class directly ~ComObject(){LIMITED_METHOD_CONTRACT;}; public: OBJECTREF m_ObjectToDataMap; //-------------------------------------------------------------------- // SupportsInterface static BOOL SupportsInterface(OBJECTREF oref, MethodTable* pIntfTable); //-------------------------------------------------------------------- // SupportsInterface static void ThrowInvalidCastException(OBJECTREF *pObj, MethodTable* pCastToMT); //----------------------------------------------------------------- // GetComIPFromRCW static IUnknown* GetComIPFromRCW(OBJECTREF *pObj, MethodTable* pIntfTable); //----------------------------------------------------------------- // GetComIPFromRCWThrowing static IUnknown* GetComIPFromRCWThrowing(OBJECTREF *pObj, MethodTable* pIntfTable); //----------------------------------------------------------- // create an empty ComObjectRef static OBJECTREF CreateComObjectRef(MethodTable* pMT); //----------------------------------------------------------- // Release all the data associated with the __ComObject. static void ReleaseAllData(OBJECTREF oref); }; #ifdef USE_CHECKED_OBJECTREFS typedef REF<ComObject> COMOBJECTREF; #else typedef ComObject* COMOBJECTREF; #endif //------------------------------------------------------------- // class UnknownWrapper, Exposed class UnknownWrapper // // //------------------------------------------------------------- class UnknownWrapper : public Object { protected: UnknownWrapper(UnknownWrapper &wrap) {LIMITED_METHOD_CONTRACT}; // dissalow copy construction. UnknownWrapper() {LIMITED_METHOD_CONTRACT;}; // don't instantiate this class directly ~UnknownWrapper() {LIMITED_METHOD_CONTRACT;}; OBJECTREF m_WrappedObject; public: OBJECTREF GetWrappedObject() { LIMITED_METHOD_CONTRACT; return m_WrappedObject; } void SetWrappedObject(OBJECTREF pWrappedObject) { LIMITED_METHOD_CONTRACT; m_WrappedObject = pWrappedObject; } }; #ifdef USE_CHECKED_OBJECTREFS typedef REF<UnknownWrapper> UNKNOWNWRAPPEROBJECTREF; #else typedef UnknownWrapper* UNKNOWNWRAPPEROBJECTREF; #endif //------------------------------------------------------------- // class DispatchWrapper, Exposed class DispatchWrapper // // //------------------------------------------------------------- class DispatchWrapper : public Object { protected: DispatchWrapper(DispatchWrapper &wrap) {LIMITED_METHOD_CONTRACT}; // dissalow copy construction. DispatchWrapper() {LIMITED_METHOD_CONTRACT;}; // don't instantiate this class directly ~DispatchWrapper() {LIMITED_METHOD_CONTRACT;}; OBJECTREF m_WrappedObject; public: OBJECTREF GetWrappedObject() { LIMITED_METHOD_CONTRACT; return m_WrappedObject; } void SetWrappedObject(OBJECTREF pWrappedObject) { LIMITED_METHOD_CONTRACT; m_WrappedObject = pWrappedObject; } }; #ifdef USE_CHECKED_OBJECTREFS typedef REF<DispatchWrapper> DISPATCHWRAPPEROBJECTREF; #else typedef DispatchWrapper* DISPATCHWRAPPEROBJECTREF; #endif //------------------------------------------------------------- // class VariantWrapper, Exposed class VARIANTWRAPPEROBJECTREF // // //------------------------------------------------------------- class VariantWrapper : public Object { protected: VariantWrapper(VariantWrapper &wrap) {LIMITED_METHOD_CONTRACT}; // dissalow copy construction. VariantWrapper() {LIMITED_METHOD_CONTRACT}; // don't instantiate this class directly ~VariantWrapper() {LIMITED_METHOD_CONTRACT}; OBJECTREF m_WrappedObject; public: OBJECTREF GetWrappedObject() { LIMITED_METHOD_CONTRACT; return m_WrappedObject; } void SetWrappedObject(OBJECTREF pWrappedObject) { LIMITED_METHOD_CONTRACT; m_WrappedObject = pWrappedObject; } }; #ifdef USE_CHECKED_OBJECTREFS typedef REF<VariantWrapper> VARIANTWRAPPEROBJECTREF; #else typedef VariantWrapper* VARIANTWRAPPEROBJECTREF; #endif //------------------------------------------------------------- // class ErrorWrapper, Exposed class ErrorWrapper // // //------------------------------------------------------------- class ErrorWrapper : public Object { protected: ErrorWrapper(ErrorWrapper &wrap) {LIMITED_METHOD_CONTRACT}; // dissalow copy construction. ErrorWrapper() {LIMITED_METHOD_CONTRACT;}; // don't instantiate this class directly ~ErrorWrapper() {LIMITED_METHOD_CONTRACT;}; INT32 m_ErrorCode; public: INT32 GetErrorCode() { LIMITED_METHOD_CONTRACT; return m_ErrorCode; } void SetErrorCode(int ErrorCode) { LIMITED_METHOD_CONTRACT; m_ErrorCode = ErrorCode; } }; #ifdef USE_CHECKED_OBJECTREFS typedef REF<ErrorWrapper> ERRORWRAPPEROBJECTREF; #else typedef ErrorWrapper* ERRORWRAPPEROBJECTREF; #endif //------------------------------------------------------------- // class CurrencyWrapper, Exposed class CurrencyWrapper // // //------------------------------------------------------------- // Keep this in sync with code:MethodTableBuilder.CheckForSystemTypes where // alignment requirement of the managed System.Decimal structure is computed. #if !defined(ALIGN_ACCESS) && !defined(FEATURE_64BIT_ALIGNMENT) #include <pshpack4.h> #endif // !ALIGN_ACCESS && !FEATURE_64BIT_ALIGNMENT class CurrencyWrapper : public Object { protected: CurrencyWrapper(CurrencyWrapper &wrap) {LIMITED_METHOD_CONTRACT}; // dissalow copy construction. CurrencyWrapper() {LIMITED_METHOD_CONTRACT;}; // don't instantiate this class directly ~CurrencyWrapper() {LIMITED_METHOD_CONTRACT;}; DECIMAL m_WrappedObject; public: DECIMAL GetWrappedObject() { LIMITED_METHOD_CONTRACT; return m_WrappedObject; } void SetWrappedObject(DECIMAL WrappedObj) { LIMITED_METHOD_CONTRACT; m_WrappedObject = WrappedObj; } }; #if !defined(ALIGN_ACCESS) && !defined(FEATURE_64BIT_ALIGNMENT) #include <poppack.h> #endif // !ALIGN_ACCESS && !FEATURE_64BIT_ALIGNMENT #ifdef USE_CHECKED_OBJECTREFS typedef REF<CurrencyWrapper> CURRENCYWRAPPEROBJECTREF; #else typedef CurrencyWrapper* CURRENCYWRAPPEROBJECTREF; #endif //------------------------------------------------------------- // class BStrWrapper, Exposed class BSTRWRAPPEROBJECTREF // // //------------------------------------------------------------- class BStrWrapper : public Object { protected: BStrWrapper(BStrWrapper &wrap) {LIMITED_METHOD_CONTRACT}; // dissalow copy construction. BStrWrapper() {LIMITED_METHOD_CONTRACT}; // don't instantiate this class directly ~BStrWrapper() {LIMITED_METHOD_CONTRACT}; STRINGREF m_WrappedObject; public: STRINGREF GetWrappedObject() { LIMITED_METHOD_CONTRACT; return m_WrappedObject; } void SetWrappedObject(STRINGREF pWrappedObject) { LIMITED_METHOD_CONTRACT; m_WrappedObject = pWrappedObject; } }; #ifdef USE_CHECKED_OBJECTREFS typedef REF<BStrWrapper> BSTRWRAPPEROBJECTREF; #else typedef BStrWrapper* BSTRWRAPPEROBJECTREF; #endif #endif // FEATURE_COMINTEROP class SafeHandle : public Object { friend class CoreLibBinder; private: // READ ME: // Modifying the order or fields of this object may require // other changes to the classlib class definition of this // object or special handling when loading this system class. Volatile<LPVOID> m_handle; Volatile<INT32> m_state; // Combined ref count and closed/disposed state (for atomicity) Volatile<CLR_BOOL> m_ownsHandle; Volatile<CLR_BOOL> m_fullyInitialized; // Did constructor finish? // Describe the bits in the m_state field above. enum StateBits { SH_State_Closed = 0x00000001, SH_State_Disposed = 0x00000002, SH_State_RefCount = 0xfffffffc, SH_RefCountOne = 4, // Amount to increment state field to yield a ref count increment of 1 }; static WORD s_IsInvalidHandleMethodSlot; static WORD s_ReleaseHandleMethodSlot; static void RunReleaseMethod(SafeHandle* psh); BOOL IsFullyInitialized() const { LIMITED_METHOD_CONTRACT; return m_fullyInitialized; } public: static void Init(); // To use the SafeHandle from native, look at the SafeHandleHolder, which // will do the AddRef & Release for you. LPVOID GetHandle() const { LIMITED_METHOD_CONTRACT; _ASSERTE(((unsigned int) m_state) >= SH_RefCountOne); return m_handle; } void AddRef(); void Release(bool fDispose = false); void SetHandle(LPVOID handle); }; void AcquireSafeHandle(SAFEHANDLEREF* s); void ReleaseSafeHandle(SAFEHANDLEREF* s); typedef Holder<SAFEHANDLEREF*, AcquireSafeHandle, ReleaseSafeHandle> SafeHandleHolder; class CriticalHandle : public Object { friend class CoreLibBinder; private: // READ ME: // Modifying the order or fields of this object may require // other changes to the classlib class definition of this // object or special handling when loading this system class. Volatile<LPVOID> m_handle; Volatile<CLR_BOOL> m_isClosed; public: LPVOID GetHandle() const { LIMITED_METHOD_CONTRACT; return m_handle; } static size_t GetHandleOffset() { LIMITED_METHOD_CONTRACT; return offsetof(CriticalHandle, m_handle); } void SetHandle(LPVOID handle) { LIMITED_METHOD_CONTRACT; m_handle = handle; } }; #ifdef USE_CHECKED_OBJECTREFS typedef REF<CriticalHandle> CRITICALHANDLE; typedef REF<CriticalHandle> CRITICALHANDLEREF; #else // USE_CHECKED_OBJECTREFS typedef CriticalHandle * CRITICALHANDLE; typedef CriticalHandle * CRITICALHANDLEREF; #endif // USE_CHECKED_OBJECTREFS // WaitHandleBase // Base class for WaitHandle class WaitHandleBase :public MarshalByRefObjectBaseObject { friend class CoreLibBinder; public: __inline LPVOID GetWaitHandle() { LIMITED_METHOD_CONTRACT; SAFEHANDLEREF safeHandle = (SAFEHANDLEREF)m_safeHandle.LoadWithoutBarrier(); return safeHandle != NULL ? safeHandle->GetHandle() : INVALID_HANDLE_VALUE; } __inline SAFEHANDLEREF GetSafeHandle() {LIMITED_METHOD_CONTRACT; return (SAFEHANDLEREF)m_safeHandle.LoadWithoutBarrier();} private: Volatile<SafeHandle*> m_safeHandle; }; #ifdef USE_CHECKED_OBJECTREFS typedef REF<WaitHandleBase> WAITHANDLEREF; #else // USE_CHECKED_OBJECTREFS typedef WaitHandleBase* WAITHANDLEREF; #endif // USE_CHECKED_OBJECTREFS // This class corresponds to System.MulticastDelegate on the managed side. class DelegateObject : public Object { friend class CheckAsmOffsets; friend class CoreLibBinder; public: BOOL IsWrapperDelegate() { LIMITED_METHOD_CONTRACT; return _methodPtrAux == NULL; } OBJECTREF GetTarget() { LIMITED_METHOD_CONTRACT; return _target; } void SetTarget(OBJECTREF target) { WRAPPER_NO_CONTRACT; SetObjectReference(&_target, target); } static int GetOffsetOfTarget() { LIMITED_METHOD_CONTRACT; return offsetof(DelegateObject, _target); } PCODE GetMethodPtr() { LIMITED_METHOD_CONTRACT; return _methodPtr; } void SetMethodPtr(PCODE methodPtr) { LIMITED_METHOD_CONTRACT; _methodPtr = methodPtr; } static int GetOffsetOfMethodPtr() { LIMITED_METHOD_CONTRACT; return offsetof(DelegateObject, _methodPtr); } PCODE GetMethodPtrAux() { LIMITED_METHOD_CONTRACT; return _methodPtrAux; } void SetMethodPtrAux(PCODE methodPtrAux) { LIMITED_METHOD_CONTRACT; _methodPtrAux = methodPtrAux; } static int GetOffsetOfMethodPtrAux() { LIMITED_METHOD_CONTRACT; return offsetof(DelegateObject, _methodPtrAux); } OBJECTREF GetInvocationList() { LIMITED_METHOD_CONTRACT; return _invocationList; } void SetInvocationList(OBJECTREF invocationList) { WRAPPER_NO_CONTRACT; SetObjectReference(&_invocationList, invocationList); } static int GetOffsetOfInvocationList() { LIMITED_METHOD_CONTRACT; return offsetof(DelegateObject, _invocationList); } INT_PTR GetInvocationCount() { LIMITED_METHOD_CONTRACT; return _invocationCount; } void SetInvocationCount(INT_PTR invocationCount) { LIMITED_METHOD_CONTRACT; _invocationCount = invocationCount; } static int GetOffsetOfInvocationCount() { LIMITED_METHOD_CONTRACT; return offsetof(DelegateObject, _invocationCount); } void SetMethodBase(OBJECTREF newMethodBase) { LIMITED_METHOD_CONTRACT; SetObjectReference((OBJECTREF*)&_methodBase, newMethodBase); } // README: // If you modify the order of these fields, make sure to update the definition in // BCL for this object. private: // System.Delegate OBJECTREF _target; OBJECTREF _methodBase; PCODE _methodPtr; PCODE _methodPtrAux; // System.MulticastDelegate OBJECTREF _invocationList; INT_PTR _invocationCount; }; #define OFFSETOF__DelegateObject__target OBJECT_SIZE /* m_pMethTab */ #define OFFSETOF__DelegateObject__methodPtr (OFFSETOF__DelegateObject__target + TARGET_POINTER_SIZE /* _target */ + TARGET_POINTER_SIZE /* _methodBase */) #define OFFSETOF__DelegateObject__methodPtrAux (OFFSETOF__DelegateObject__methodPtr + TARGET_POINTER_SIZE /* _methodPtr */) #ifdef USE_CHECKED_OBJECTREFS typedef REF<DelegateObject> DELEGATEREF; #else // USE_CHECKED_OBJECTREFS typedef DelegateObject* DELEGATEREF; #endif // USE_CHECKED_OBJECTREFS struct StackTraceElement; class ClrDataAccess; typedef DPTR(StackTraceElement) PTR_StackTraceElement; class StackTraceArray { struct ArrayHeader { size_t m_size; Thread * m_thread; }; typedef DPTR(ArrayHeader) PTR_ArrayHeader; public: StackTraceArray() : m_array(static_cast<I1Array *>(NULL)) { WRAPPER_NO_CONTRACT; } StackTraceArray(I1ARRAYREF array) : m_array(array) { LIMITED_METHOD_CONTRACT; } void Swap(StackTraceArray & rhs) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; SUPPORTS_DAC; I1ARRAYREF t = m_array; m_array = rhs.m_array; rhs.m_array = t; } size_t Size() const { WRAPPER_NO_CONTRACT; if (!m_array) return 0; else return GetSize(); } StackTraceElement const & operator[](size_t index) const; StackTraceElement & operator[](size_t index); void Append(StackTraceElement const * begin, StackTraceElement const * end); I1ARRAYREF Get() const { LIMITED_METHOD_DAC_CONTRACT; return m_array; } // Deep copies the array void CopyFrom(StackTraceArray const & src); private: StackTraceArray(StackTraceArray const & rhs) = delete; StackTraceArray & operator=(StackTraceArray const & rhs) = delete; void Grow(size_t size); void EnsureThreadAffinity(); void CheckState() const; size_t Capacity() const { WRAPPER_NO_CONTRACT; assert(!!m_array); return m_array->GetNumComponents(); } size_t GetSize() const { WRAPPER_NO_CONTRACT; return GetHeader()->m_size; } void SetSize(size_t size) { WRAPPER_NO_CONTRACT; GetHeader()->m_size = size; } Thread * GetObjectThread() const { WRAPPER_NO_CONTRACT; return GetHeader()->m_thread; } void SetObjectThread() { WRAPPER_NO_CONTRACT; GetHeader()->m_thread = GetThread(); } StackTraceElement const * GetData() const { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; return dac_cast<PTR_StackTraceElement>(GetRaw() + sizeof(ArrayHeader)); } PTR_StackTraceElement GetData() { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; return dac_cast<PTR_StackTraceElement>(GetRaw() + sizeof(ArrayHeader)); } I1 const * GetRaw() const { WRAPPER_NO_CONTRACT; assert(!!m_array); return const_cast<I1ARRAYREF &>(m_array)->GetDirectPointerToNonObjectElements(); } PTR_I1 GetRaw() { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; assert(!!m_array); return dac_cast<PTR_I1>(m_array->GetDirectPointerToNonObjectElements()); } ArrayHeader const * GetHeader() const { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; return dac_cast<PTR_ArrayHeader>(GetRaw()); } PTR_ArrayHeader GetHeader() { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; return dac_cast<PTR_ArrayHeader>(GetRaw()); } void SetArray(I1ARRAYREF const & arr) { LIMITED_METHOD_CONTRACT; m_array = arr; } private: // put only things here that can be protected with GCPROTECT I1ARRAYREF m_array; }; #ifdef FEATURE_COLLECTIBLE_TYPES class LoaderAllocatorScoutObject : public Object { friend class CoreLibBinder; friend class LoaderAllocatorObject; protected: LoaderAllocator * m_nativeLoaderAllocator; }; #ifdef USE_CHECKED_OBJECTREFS typedef REF<LoaderAllocatorScoutObject> LOADERALLOCATORSCOUTREF; #else // USE_CHECKED_OBJECTREFS typedef LoaderAllocatorScoutObject* LOADERALLOCATORSCOUTREF; #endif // USE_CHECKED_OBJECTREFS class LoaderAllocatorObject : public Object { friend class CoreLibBinder; public: PTRARRAYREF GetHandleTable() { LIMITED_METHOD_DAC_CONTRACT; return (PTRARRAYREF)m_pSlots; } void SetHandleTable(PTRARRAYREF handleTable) { LIMITED_METHOD_CONTRACT; SetObjectReference(&m_pSlots, (OBJECTREF)handleTable); } INT32 GetSlotsUsed() { LIMITED_METHOD_CONTRACT; return m_slotsUsed; } void SetSlotsUsed(INT32 newSlotsUsed) { LIMITED_METHOD_CONTRACT; m_slotsUsed = newSlotsUsed; } void SetNativeLoaderAllocator(LoaderAllocator * pLoaderAllocator) { LIMITED_METHOD_CONTRACT; m_pLoaderAllocatorScout->m_nativeLoaderAllocator = pLoaderAllocator; } // README: // If you modify the order of these fields, make sure to update the definition in // BCL for this object. protected: LOADERALLOCATORSCOUTREF m_pLoaderAllocatorScout; OBJECTREF m_pSlots; INT32 m_slotsUsed; OBJECTREF m_methodInstantiationsTable; }; #ifdef USE_CHECKED_OBJECTREFS typedef REF<LoaderAllocatorObject> LOADERALLOCATORREF; #else // USE_CHECKED_OBJECTREFS typedef DPTR(LoaderAllocatorObject) PTR_LoaderAllocatorObject; typedef PTR_LoaderAllocatorObject LOADERALLOCATORREF; #endif // USE_CHECKED_OBJECTREFS #endif // FEATURE_COLLECTIBLE_TYPES #if !defined(DACCESS_COMPILE) // Define the lock used to access stacktrace from an exception object EXTERN_C SpinLock g_StackTraceArrayLock; #endif // !defined(DACCESS_COMPILE) // This class corresponds to Exception on the managed side. typedef DPTR(class ExceptionObject) PTR_ExceptionObject; #include "pshpack4.h" class ExceptionObject : public Object { friend class CoreLibBinder; public: void SetHResult(HRESULT hr) { LIMITED_METHOD_CONTRACT; _HResult = hr; } HRESULT GetHResult() { LIMITED_METHOD_CONTRACT; return _HResult; } void SetXCode(DWORD code) { LIMITED_METHOD_CONTRACT; _xcode = code; } DWORD GetXCode() { LIMITED_METHOD_CONTRACT; return _xcode; } void SetXPtrs(void* xptrs) { LIMITED_METHOD_CONTRACT; _xptrs = xptrs; } void* GetXPtrs() { LIMITED_METHOD_CONTRACT; return _xptrs; } void SetStackTrace(I1ARRAYREF stackTrace, PTRARRAYREF dynamicMethodArray); void GetStackTrace(StackTraceArray & stackTrace, PTRARRAYREF * outDynamicMethodArray = NULL) const; I1ARRAYREF GetStackTraceArrayObject() const { LIMITED_METHOD_DAC_CONTRACT; return _stackTrace; } void SetInnerException(OBJECTREF innerException) { WRAPPER_NO_CONTRACT; SetObjectReference((OBJECTREF*)&_innerException, (OBJECTREF)innerException); } OBJECTREF GetInnerException() { LIMITED_METHOD_DAC_CONTRACT; return VolatileLoadWithoutBarrierOBJECTREF(&_innerException); } // Returns the innermost exception object - equivalent of the // managed System.Exception.GetBaseException method. OBJECTREF GetBaseException() { LIMITED_METHOD_CONTRACT; // Loop and get the innermost exception object OBJECTREF oInnerMostException = NULL; OBJECTREF oCurrent = NULL; oCurrent = GetInnerException(); while(oCurrent != NULL) { oInnerMostException = oCurrent; oCurrent = ((ExceptionObject*)(Object *)OBJECTREFToObject(oCurrent))->GetInnerException(); } // return the innermost exception return oInnerMostException; } void SetMessage(STRINGREF message) { WRAPPER_NO_CONTRACT; SetObjectReference((OBJECTREF*)&_message, (OBJECTREF)message); } STRINGREF GetMessage() { LIMITED_METHOD_DAC_CONTRACT; return _message; } void SetStackTraceString(STRINGREF stackTraceString) { WRAPPER_NO_CONTRACT; SetObjectReference((OBJECTREF*)&_stackTraceString, (OBJECTREF)stackTraceString); } STRINGREF GetStackTraceString() { LIMITED_METHOD_DAC_CONTRACT; return _stackTraceString; } STRINGREF GetRemoteStackTraceString() { LIMITED_METHOD_DAC_CONTRACT; return (STRINGREF)VolatileLoadWithoutBarrierOBJECTREF(&_remoteStackTraceString); } void SetHelpURL(STRINGREF helpURL) { WRAPPER_NO_CONTRACT; SetObjectReference((OBJECTREF*)&_helpURL, (OBJECTREF)helpURL); } void SetSource(STRINGREF source) { WRAPPER_NO_CONTRACT; SetObjectReference((OBJECTREF*)&_source, (OBJECTREF)source); } void ClearStackTraceForThrow() { WRAPPER_NO_CONTRACT; SetObjectReference((OBJECTREF*)&_remoteStackTraceString, NULL); SetObjectReference((OBJECTREF*)&_stackTrace, NULL); SetObjectReference((OBJECTREF*)&_stackTraceString, NULL); } void ClearStackTracePreservingRemoteStackTrace() { WRAPPER_NO_CONTRACT; SetObjectReference((OBJECTREF*)&_stackTrace, NULL); SetObjectReference((OBJECTREF*)&_stackTraceString, NULL); } // This method will set the reference to the array // containing the watson bucket information (in byte[] form). void SetWatsonBucketReference(OBJECTREF oWatsonBucketArray) { WRAPPER_NO_CONTRACT; SetObjectReference((OBJECTREF*)&_watsonBuckets, (OBJECTREF)oWatsonBucketArray); } // This method will return the reference to the array // containing the watson buckets U1ARRAYREF GetWatsonBucketReference() { LIMITED_METHOD_CONTRACT; return (U1ARRAYREF)VolatileLoadWithoutBarrierOBJECTREF(&_watsonBuckets); } // This method will return a BOOL to indicate if the // watson buckets are present or not. BOOL AreWatsonBucketsPresent() { LIMITED_METHOD_CONTRACT; return (GetWatsonBucketReference() != NULL)?TRUE:FALSE; } // This method will save the IP to be used for watson bucketing. void SetIPForWatsonBuckets(UINT_PTR ip) { LIMITED_METHOD_CONTRACT; _ipForWatsonBuckets = ip; } // This method will return a BOOL to indicate if Watson bucketing IP // is present (or not). BOOL IsIPForWatsonBucketsPresent() { LIMITED_METHOD_CONTRACT; return (_ipForWatsonBuckets != NULL); } // This method returns the IP for Watson Buckets. UINT_PTR GetIPForWatsonBuckets() { LIMITED_METHOD_CONTRACT; return VolatileLoadWithoutBarrier(&_ipForWatsonBuckets); } // README: // If you modify the order of these fields, make sure to update the definition in // BCL for this object. private: OBJECTREF _exceptionMethod; //Needed for serialization. STRINGREF _message; OBJECTREF _data; OBJECTREF _innerException; STRINGREF _helpURL; I1ARRAYREF _stackTrace; U1ARRAYREF _watsonBuckets; STRINGREF _stackTraceString; //Needed for serialization. STRINGREF _remoteStackTraceString; PTRARRAYREF _dynamicMethods; STRINGREF _source; // Mainly used by VB. UINT_PTR _ipForWatsonBuckets; // Contains the IP of exception for watson bucketing void* _xptrs; INT32 _xcode; INT32 _HResult; }; // Defined in Contracts.cs enum ContractFailureKind { CONTRACT_FAILURE_PRECONDITION = 0, CONTRACT_FAILURE_POSTCONDITION, CONTRACT_FAILURE_POSTCONDITION_ON_EXCEPTION, CONTRACT_FAILURE_INVARIANT, CONTRACT_FAILURE_ASSERT, CONTRACT_FAILURE_ASSUME, }; typedef DPTR(class ContractExceptionObject) PTR_ContractExceptionObject; class ContractExceptionObject : public ExceptionObject { friend class CoreLibBinder; public: ContractFailureKind GetContractFailureKind() { LIMITED_METHOD_CONTRACT; return static_cast<ContractFailureKind>(_Kind); } private: // keep these in sync with ndp/clr/src/bcl/system/diagnostics/contracts/contractsbcl.cs STRINGREF _UserMessage; STRINGREF _Condition; INT32 _Kind; }; #include "poppack.h" #ifdef USE_CHECKED_OBJECTREFS typedef REF<ContractExceptionObject> CONTRACTEXCEPTIONREF; #else // USE_CHECKED_OBJECTREFS typedef PTR_ContractExceptionObject CONTRACTEXCEPTIONREF; #endif // USE_CHECKED_OBJECTREFS //=============================================================================== // #NullableFeature // #NullableArchitecture // // In a nutshell it is counterintuitive to have a boxed Nullable<T>, since a boxed // object already has a representation for null (the null pointer), and having // multiple representations for the 'not present' value just causes grief. Thus the // feature is build make Nullable<T> box to a boxed<T> (not boxed<Nullable<T>). // // We want to do this in a way that does not impact the perf of the runtime in the // non-nullable case. // // To do this we need to // * Modify the boxing helper code:JIT_Box (we don't need a special one because // the JIT inlines the common case, so this only gets call in uncommon cases) // * Make a new helper for the Unbox case (see code:JIT_Unbox_Nullable) // * Plumb the JIT to ask for what kind of Boxing helper is needed // (see code:CEEInfo.getBoxHelper, code:CEEInfo.getUnBoxHelper // * change all the places in the CLR where we box or unbox by hand, and force // them to use code:MethodTable.Box, and code:MethodTable.Unbox which in // turn call code:Nullable.Box and code:Nullable.UnBox, most of these // are in reflection, and remoting (passing and returning value types). // // #NullableVerification // // Sadly, the IL Verifier also needs to know about this change. Basically the 'box' // instruction returns a boxed(T) (not a boxed(Nullable<T>)) for the purposes of // verfication. The JIT finds out what box returns by calling back to the EE with // the code:CEEInfo.getTypeForBox API. // // #NullableDebugging // // Sadly, because the debugger also does its own boxing 'by hand' for expression // evaluation inside visual studio, it measn that debuggers also need to be aware // of the fact that Nullable<T> boxes to a boxed<T>. It is the responcibility of // debuggers to follow this convention (which is why this is sad). // //=============================================================================== // Nullable represents the managed generic value type Nullable<T> // // The runtime has special logic for this value class. When it is boxed // it becomes either null or a boxed T. Similarly a boxed T can be unboxed // either as a T (as normal), or as a Nullable<T> // // See code:Nullable#NullableArchitecture for more. // class Nullable { Nullable(); // This is purposefully undefined. Do not make instances // of this class. public: static void CheckFieldOffsets(TypeHandle nullableType); static BOOL IsNullableType(TypeHandle nullableType); static BOOL IsNullableForType(TypeHandle nullableType, MethodTable* paramMT); static BOOL IsNullableForTypeNoGC(TypeHandle nullableType, MethodTable* paramMT); static OBJECTREF Box(void* src, MethodTable* nullable); static BOOL UnBox(void* dest, OBJECTREF boxedVal, MethodTable* destMT); static BOOL UnBoxNoGC(void* dest, OBJECTREF boxedVal, MethodTable* destMT); static BOOL UnBoxIntoArgNoGC(ArgDestination *argDest, OBJECTREF boxedVal, MethodTable* destMT); static void UnBoxNoCheck(void* dest, OBJECTREF boxedVal, MethodTable* destMT); static OBJECTREF BoxedNullableNull(TypeHandle nullableType) { return 0; } // if 'Obj' is a true boxed nullable, return the form we want (either null or a boxed T) static OBJECTREF NormalizeBox(OBJECTREF obj); static inline CLR_BOOL HasValue(void *src, MethodTable *nullableMT) { Nullable *nullable = (Nullable *)src; return *(nullable->HasValueAddr(nullableMT)); } static inline void *Value(void *src, MethodTable *nullableMT) { Nullable *nullable = (Nullable *)src; return nullable->ValueAddr(nullableMT); } private: static BOOL IsNullableForTypeHelper(MethodTable* nullableMT, MethodTable* paramMT); static BOOL IsNullableForTypeHelperNoGC(MethodTable* nullableMT, MethodTable* paramMT); CLR_BOOL* HasValueAddr(MethodTable* nullableMT); void* ValueAddr(MethodTable* nullableMT); }; #ifdef USE_CHECKED_OBJECTREFS typedef REF<ExceptionObject> EXCEPTIONREF; #else // USE_CHECKED_OBJECTREFS typedef PTR_ExceptionObject EXCEPTIONREF; #endif // USE_CHECKED_OBJECTREFS class GCHeapHashObject : public Object { #ifdef DACCESS_COMPILE friend class ClrDataAccess; #endif friend class GCHeap; friend class JIT_TrialAlloc; friend class CheckAsmOffsets; friend class COMString; friend class CoreLibBinder; private: BASEARRAYREF _data; INT32 _count; INT32 _deletedCount; public: INT32 GetCount() { LIMITED_METHOD_CONTRACT; return _count; } void IncrementCount(bool replacingDeletedItem) { LIMITED_METHOD_CONTRACT; ++_count; if (replacingDeletedItem) --_deletedCount; } void DecrementCount(bool deletingItem) { LIMITED_METHOD_CONTRACT; --_count; if (deletingItem) ++_deletedCount; } INT32 GetDeletedCount() { LIMITED_METHOD_CONTRACT; return _deletedCount; } void SetDeletedCountToZero() { LIMITED_METHOD_CONTRACT; _deletedCount = 0; } INT32 GetCapacity() { LIMITED_METHOD_CONTRACT; if (_data == NULL) return 0; else return (_data->GetNumComponents()); } BASEARRAYREF GetData() { LIMITED_METHOD_CONTRACT; return _data; } void SetTable(BASEARRAYREF data) { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_COOPERATIVE; SetObjectReference((OBJECTREF*)&_data, (OBJECTREF)data); } protected: GCHeapHashObject() {LIMITED_METHOD_CONTRACT; } ~GCHeapHashObject() {LIMITED_METHOD_CONTRACT; } }; typedef DPTR(GCHeapHashObject) PTR_GCHeapHashObject; #ifdef USE_CHECKED_OBJECTREFS typedef REF<GCHeapHashObject> GCHEAPHASHOBJECTREF; #else // USE_CHECKED_OBJECTREFS typedef PTR_GCHeapHashObject GCHEAPHASHOBJECTREF; #endif // USE_CHECKED_OBJECTREFS class LAHashDependentHashTrackerObject : public Object { #ifdef DACCESS_COMPILE friend class ClrDataAccess; #endif friend class CheckAsmOffsets; friend class CoreLibBinder; private: OBJECTHANDLE _dependentHandle; LoaderAllocator* _loaderAllocator; public: bool IsLoaderAllocatorLive(); bool IsTrackerFor(LoaderAllocator *pLoaderAllocator) { if (pLoaderAllocator != _loaderAllocator) return false; return IsLoaderAllocatorLive(); } void GetDependentAndLoaderAllocator(OBJECTREF *pLoaderAllocatorRef, GCHEAPHASHOBJECTREF *pGCHeapHash); // Be careful with this. This isn't safe to use unless something is keeping the LoaderAllocator live, or there is no intention to dereference this pointer LoaderAllocator* GetLoaderAllocatorUnsafe() { return _loaderAllocator; } void Init(OBJECTHANDLE dependentHandle, LoaderAllocator* loaderAllocator) { LIMITED_METHOD_CONTRACT; _dependentHandle = dependentHandle; _loaderAllocator = loaderAllocator; } }; class LAHashKeyToTrackersObject : public Object { #ifdef DACCESS_COMPILE friend class ClrDataAccess; #endif friend class CheckAsmOffsets; friend class CoreLibBinder; public: // _trackerOrTrackerSet is either a reference to a LAHashDependentHashTracker, or to a GCHeapHash of LAHashDependentHashTracker objects. OBJECTREF _trackerOrTrackerSet; // _laLocalKeyValueStore holds an object that represents a Key value (which must always be valid for the lifetime of the // CrossLoaderAllocatorHeapHash, and the values which must also be valid for that entire lifetime. When a value might // have a shorter lifetime it is accessed through the _trackerOrTrackerSet variable, which allows access to hashtables which // are associated with that remote loaderallocator through a dependent handle, so that lifetime can be managed. OBJECTREF _laLocalKeyValueStore; }; typedef DPTR(LAHashDependentHashTrackerObject) PTR_LAHashDependentHashTrackerObject; typedef DPTR(LAHashKeyToTrackersObject) PTR_LAHashKeyToTrackersObject; #ifdef USE_CHECKED_OBJECTREFS typedef REF<LAHashDependentHashTrackerObject> LAHASHDEPENDENTHASHTRACKERREF; typedef REF<LAHashKeyToTrackersObject> LAHASHKEYTOTRACKERSREF; #else // USE_CHECKED_OBJECTREFS typedef PTR_LAHashDependentHashTrackerObject LAHASHDEPENDENTHASHTRACKERREF; typedef PTR_LAHashKeyToTrackersObject LAHASHKEYTOTRACKERSREF; #endif // USE_CHECKED_OBJECTREFS #endif // _OBJECT_H_
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/pal/src/libunwind/include/tdep-x86_64/libunwind_i.h
/* libunwind - a platform-independent unwind library Copyright (C) 2002-2005 Hewlett-Packard Co Contributed by David Mosberger-Tang <[email protected]> Modified for x86_64 by Max Asbock <[email protected]> This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef X86_64_LIBUNWIND_I_H #define X86_64_LIBUNWIND_I_H /* Target-dependent definitions that are internal to libunwind but need to be shared with target-independent code. */ #include <stdint.h> #include <stdlib.h> #include <stdatomic.h> #include <libunwind.h> #include "elf64.h" #include "mempool.h" #include "dwarf.h" typedef enum { UNW_X86_64_FRAME_ALIGNED = -3, /* frame stack pointer aligned */ UNW_X86_64_FRAME_STANDARD = -2, /* regular rbp, rsp +/- offset */ UNW_X86_64_FRAME_SIGRETURN = -1, /* special sigreturn frame */ UNW_X86_64_FRAME_OTHER = 0, /* not cacheable (special or unrecognised) */ UNW_X86_64_FRAME_GUESSED = 1 /* guessed it was regular, but not known */ } unw_tdep_frame_type_t; typedef struct { uint64_t virtual_address; int64_t frame_type : 3; /* unw_tdep_frame_type_t classification */ int64_t last_frame : 1; /* non-zero if last frame in chain */ int64_t cfa_reg_rsp : 1; /* cfa dwarf base register is rsp vs. rbp */ int64_t cfa_reg_offset : 29; /* cfa is at this offset from base register value */ int64_t rbp_cfa_offset : 15; /* rbp saved at this offset from cfa (-1 = not saved) */ int64_t rsp_cfa_offset : 15; /* rsp saved at this offset from cfa (-1 = not saved) */ } unw_tdep_frame_t; struct unw_addr_space { struct unw_accessors acc; unw_caching_policy_t caching_policy; _Atomic uint32_t cache_generation; unw_word_t dyn_generation; /* see dyn-common.h */ unw_word_t dyn_info_list_addr; /* (cached) dyn_info_list_addr */ struct dwarf_rs_cache global_cache; struct unw_debug_frame_list *debug_frames; }; struct cursor { struct dwarf_cursor dwarf; /* must be first */ unw_tdep_frame_t frame_info; /* quick tracing assist info */ /* Format of sigcontext structure and address at which it is stored: */ enum { X86_64_SCF_NONE, /* no signal frame encountered */ X86_64_SCF_LINUX_RT_SIGFRAME, /* Linux ucontext_t */ X86_64_SCF_FREEBSD_SIGFRAME, /* FreeBSD signal frame */ X86_64_SCF_FREEBSD_SYSCALL, /* FreeBSD syscall */ X86_64_SCF_SOLARIS_SIGFRAME, /* illumos/Solaris signal frame */ } sigcontext_format; unw_word_t sigcontext_addr; }; #define AS_ARG_UCONTEXT_MASK ~0x1UL #define AS_ARG_VALIDATE_MASK 0x1UL #define AS_ARG_GET_UC_PTR(arg) \ ((ucontext_t *) ((uintptr_t) arg & AS_ARG_UCONTEXT_MASK)) #define AS_ARG_GET_VALIDATE(arg) \ ((int) ((uintptr_t) arg & AS_ARG_VALIDATE_MASK)) static inline ucontext_t * dwarf_get_uc(const struct dwarf_cursor *cursor) { assert(cursor->as == unw_local_addr_space); return AS_ARG_GET_UC_PTR(cursor->as_arg); } static inline int dwarf_get_validate(const struct dwarf_cursor *cursor) { assert(cursor->as == unw_local_addr_space); return AS_ARG_GET_VALIDATE(cursor->as_arg); } static inline void dwarf_set_validate(const struct dwarf_cursor *cursor, const int validate) { assert(cursor->as == unw_local_addr_space); uintptr_t *packed_args = (uintptr_t *) &cursor->as_arg; *packed_args |= (AS_ARG_VALIDATE_MASK & validate); } static inline void * dwarf_build_as_arg(const ucontext_t *uc, const int validate) { uintptr_t packed_args = (uintptr_t) uc; assert((packed_args & AS_ARG_VALIDATE_MASK) == 0); packed_args |= (AS_ARG_VALIDATE_MASK & validate); return (void *) packed_args; } #define DWARF_GET_LOC(l) ((l).val) # define DWARF_LOC_TYPE_MEM (0 << 0) # define DWARF_LOC_TYPE_FP (1 << 0) # define DWARF_LOC_TYPE_REG (1 << 1) # define DWARF_LOC_TYPE_VAL (1 << 2) # define DWARF_IS_REG_LOC(l) (((l).type & DWARF_LOC_TYPE_REG) != 0) # define DWARF_IS_FP_LOC(l) (((l).type & DWARF_LOC_TYPE_FP) != 0) # define DWARF_IS_MEM_LOC(l) ((l).type == DWARF_LOC_TYPE_MEM) # define DWARF_IS_VAL_LOC(l) (((l).type & DWARF_LOC_TYPE_VAL) != 0) # define DWARF_LOC(r, t) ((dwarf_loc_t) { .val = (r), .type = (t) }) # define DWARF_VAL_LOC(c,v) DWARF_LOC ((v), DWARF_LOC_TYPE_VAL) # define DWARF_MEM_LOC(c,m) DWARF_LOC ((m), DWARF_LOC_TYPE_MEM) #ifdef UNW_LOCAL_ONLY # define DWARF_NULL_LOC DWARF_LOC (0, 0) # define DWARF_IS_NULL_LOC(l) (DWARF_GET_LOC (l) == 0) # define DWARF_REG_LOC(c,r) (DWARF_LOC((unw_word_t) \ x86_64_r_uc_addr(dwarf_get_uc(c), (r)), 0)) # define DWARF_FPREG_LOC(c,r) (DWARF_LOC((unw_word_t) \ x86_64_r_uc_addr(dwarf_get_uc(c), (r)), 0)) #else /* !UNW_LOCAL_ONLY */ # define DWARF_NULL_LOC DWARF_LOC (0, 0) static inline int dwarf_is_null_loc(dwarf_loc_t l) { return l.val == 0 && l.type == 0; } # define DWARF_IS_NULL_LOC(l) dwarf_is_null_loc(l) # define DWARF_REG_LOC(c,r) DWARF_LOC((r), DWARF_LOC_TYPE_REG) # define DWARF_FPREG_LOC(c,r) DWARF_LOC((r), (DWARF_LOC_TYPE_REG \ | DWARF_LOC_TYPE_FP)) #endif /* !UNW_LOCAL_ONLY */ static inline int dwarf_getfp (struct dwarf_cursor *c, dwarf_loc_t loc, unw_fpreg_t *val) { if (DWARF_IS_NULL_LOC (loc)) return -UNW_EBADREG; abort (); } static inline int dwarf_putfp (struct dwarf_cursor *c, dwarf_loc_t loc, unw_fpreg_t val) { if (DWARF_IS_NULL_LOC (loc)) return -UNW_EBADREG; abort (); } static inline int dwarf_get (struct dwarf_cursor *c, dwarf_loc_t loc, unw_word_t *val) { if (DWARF_IS_NULL_LOC (loc)) return -UNW_EBADREG; if (DWARF_IS_REG_LOC (loc)) return (*c->as->acc.access_reg) (c->as, DWARF_GET_LOC (loc), val, 0, c->as_arg); if (DWARF_IS_MEM_LOC (loc)) return (*c->as->acc.access_mem) (c->as, DWARF_GET_LOC (loc), val, 0, c->as_arg); assert(DWARF_IS_VAL_LOC (loc)); *val = DWARF_GET_LOC (loc); return 0; } static inline int dwarf_put (struct dwarf_cursor *c, dwarf_loc_t loc, unw_word_t val) { assert(!DWARF_IS_VAL_LOC (loc)); if (DWARF_IS_NULL_LOC (loc)) return -UNW_EBADREG; if (DWARF_IS_REG_LOC (loc)) return (*c->as->acc.access_reg) (c->as, DWARF_GET_LOC (loc), &val, 1, c->as_arg); else return (*c->as->acc.access_mem) (c->as, DWARF_GET_LOC (loc), &val, 1, c->as_arg); } #define tdep_getcontext_trace UNW_ARCH_OBJ(getcontext_trace) #define tdep_init_done UNW_OBJ(init_done) #define tdep_init_mem_validate UNW_OBJ(init_mem_validate) #define tdep_init UNW_OBJ(init) /* Platforms that support UNW_INFO_FORMAT_TABLE need to define tdep_search_unwind_table. */ #define tdep_search_unwind_table dwarf_search_unwind_table #define tdep_find_unwind_table dwarf_find_unwind_table #define tdep_get_elf_image UNW_ARCH_OBJ(get_elf_image) #define tdep_get_exe_image_path UNW_ARCH_OBJ(get_exe_image_path) #define tdep_access_reg UNW_OBJ(access_reg) #define tdep_access_fpreg UNW_OBJ(access_fpreg) #if __linux__ # define tdep_fetch_frame UNW_OBJ(fetch_frame) # define tdep_cache_frame UNW_OBJ(cache_frame) # define tdep_reuse_frame UNW_OBJ(reuse_frame) #else # define tdep_fetch_frame(c,ip,n) do {} while(0) # define tdep_cache_frame(c) 0 # define tdep_reuse_frame(c,frame) do {} while(0) #endif #define tdep_stash_frame UNW_OBJ(stash_frame) #define tdep_trace UNW_OBJ(tdep_trace) #define x86_64_r_uc_addr UNW_OBJ(r_uc_addr) #ifdef UNW_LOCAL_ONLY # define tdep_find_proc_info(c,ip,n) \ dwarf_find_proc_info((c)->as, (ip), &(c)->pi, (n), \ (c)->as_arg) # define tdep_put_unwind_info(as,pi,arg) \ dwarf_put_unwind_info((as), (pi), (arg)) #else # define tdep_find_proc_info(c,ip,n) \ (*(c)->as->acc.find_proc_info)((c)->as, (ip), &(c)->pi, (n), \ (c)->as_arg) # define tdep_put_unwind_info(as,pi,arg) \ (*(as)->acc.put_unwind_info)((as), (pi), (arg)) #endif #define tdep_get_as(c) ((c)->dwarf.as) #define tdep_get_as_arg(c) ((c)->dwarf.as_arg) #define tdep_get_ip(c) ((c)->dwarf.ip) #define tdep_big_endian(as) 0 extern atomic_bool tdep_init_done; extern void tdep_init (void); extern void tdep_init_mem_validate (void); extern int tdep_search_unwind_table (unw_addr_space_t as, unw_word_t ip, unw_dyn_info_t *di, unw_proc_info_t *pi, int need_unwind_info, void *arg); extern void *x86_64_r_uc_addr (ucontext_t *uc, int reg); extern int tdep_get_elf_image (struct elf_image *ei, pid_t pid, unw_word_t ip, unsigned long *segbase, unsigned long *mapoff, char *path, size_t pathlen); extern void tdep_get_exe_image_path (char *path); extern int tdep_access_reg (struct cursor *c, unw_regnum_t reg, unw_word_t *valp, int write); extern int tdep_access_fpreg (struct cursor *c, unw_regnum_t reg, unw_fpreg_t *valp, int write); #if __linux__ extern void tdep_fetch_frame (struct dwarf_cursor *c, unw_word_t ip, int need_unwind_info); extern int tdep_cache_frame (struct dwarf_cursor *c); extern void tdep_reuse_frame (struct dwarf_cursor *c, int frame); extern void tdep_stash_frame (struct dwarf_cursor *c, struct dwarf_reg_state *rs); #endif extern int tdep_getcontext_trace (unw_tdep_context_t *); extern int tdep_trace (unw_cursor_t *cursor, void **addresses, int *n); #endif /* X86_64_LIBUNWIND_I_H */
/* libunwind - a platform-independent unwind library Copyright (C) 2002-2005 Hewlett-Packard Co Contributed by David Mosberger-Tang <[email protected]> Modified for x86_64 by Max Asbock <[email protected]> This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef X86_64_LIBUNWIND_I_H #define X86_64_LIBUNWIND_I_H /* Target-dependent definitions that are internal to libunwind but need to be shared with target-independent code. */ #include <stdint.h> #include <stdlib.h> #include <stdatomic.h> #include <libunwind.h> #include "elf64.h" #include "mempool.h" #include "dwarf.h" typedef enum { UNW_X86_64_FRAME_ALIGNED = -3, /* frame stack pointer aligned */ UNW_X86_64_FRAME_STANDARD = -2, /* regular rbp, rsp +/- offset */ UNW_X86_64_FRAME_SIGRETURN = -1, /* special sigreturn frame */ UNW_X86_64_FRAME_OTHER = 0, /* not cacheable (special or unrecognised) */ UNW_X86_64_FRAME_GUESSED = 1 /* guessed it was regular, but not known */ } unw_tdep_frame_type_t; typedef struct { uint64_t virtual_address; int64_t frame_type : 3; /* unw_tdep_frame_type_t classification */ int64_t last_frame : 1; /* non-zero if last frame in chain */ int64_t cfa_reg_rsp : 1; /* cfa dwarf base register is rsp vs. rbp */ int64_t cfa_reg_offset : 29; /* cfa is at this offset from base register value */ int64_t rbp_cfa_offset : 15; /* rbp saved at this offset from cfa (-1 = not saved) */ int64_t rsp_cfa_offset : 15; /* rsp saved at this offset from cfa (-1 = not saved) */ } unw_tdep_frame_t; struct unw_addr_space { struct unw_accessors acc; unw_caching_policy_t caching_policy; _Atomic uint32_t cache_generation; unw_word_t dyn_generation; /* see dyn-common.h */ unw_word_t dyn_info_list_addr; /* (cached) dyn_info_list_addr */ struct dwarf_rs_cache global_cache; struct unw_debug_frame_list *debug_frames; }; struct cursor { struct dwarf_cursor dwarf; /* must be first */ unw_tdep_frame_t frame_info; /* quick tracing assist info */ /* Format of sigcontext structure and address at which it is stored: */ enum { X86_64_SCF_NONE, /* no signal frame encountered */ X86_64_SCF_LINUX_RT_SIGFRAME, /* Linux ucontext_t */ X86_64_SCF_FREEBSD_SIGFRAME, /* FreeBSD signal frame */ X86_64_SCF_FREEBSD_SYSCALL, /* FreeBSD syscall */ X86_64_SCF_SOLARIS_SIGFRAME, /* illumos/Solaris signal frame */ } sigcontext_format; unw_word_t sigcontext_addr; }; #define AS_ARG_UCONTEXT_MASK ~0x1UL #define AS_ARG_VALIDATE_MASK 0x1UL #define AS_ARG_GET_UC_PTR(arg) \ ((ucontext_t *) ((uintptr_t) arg & AS_ARG_UCONTEXT_MASK)) #define AS_ARG_GET_VALIDATE(arg) \ ((int) ((uintptr_t) arg & AS_ARG_VALIDATE_MASK)) static inline ucontext_t * dwarf_get_uc(const struct dwarf_cursor *cursor) { assert(cursor->as == unw_local_addr_space); return AS_ARG_GET_UC_PTR(cursor->as_arg); } static inline int dwarf_get_validate(const struct dwarf_cursor *cursor) { assert(cursor->as == unw_local_addr_space); return AS_ARG_GET_VALIDATE(cursor->as_arg); } static inline void dwarf_set_validate(const struct dwarf_cursor *cursor, const int validate) { assert(cursor->as == unw_local_addr_space); uintptr_t *packed_args = (uintptr_t *) &cursor->as_arg; *packed_args |= (AS_ARG_VALIDATE_MASK & validate); } static inline void * dwarf_build_as_arg(const ucontext_t *uc, const int validate) { uintptr_t packed_args = (uintptr_t) uc; assert((packed_args & AS_ARG_VALIDATE_MASK) == 0); packed_args |= (AS_ARG_VALIDATE_MASK & validate); return (void *) packed_args; } #define DWARF_GET_LOC(l) ((l).val) # define DWARF_LOC_TYPE_MEM (0 << 0) # define DWARF_LOC_TYPE_FP (1 << 0) # define DWARF_LOC_TYPE_REG (1 << 1) # define DWARF_LOC_TYPE_VAL (1 << 2) # define DWARF_IS_REG_LOC(l) (((l).type & DWARF_LOC_TYPE_REG) != 0) # define DWARF_IS_FP_LOC(l) (((l).type & DWARF_LOC_TYPE_FP) != 0) # define DWARF_IS_MEM_LOC(l) ((l).type == DWARF_LOC_TYPE_MEM) # define DWARF_IS_VAL_LOC(l) (((l).type & DWARF_LOC_TYPE_VAL) != 0) # define DWARF_LOC(r, t) ((dwarf_loc_t) { .val = (r), .type = (t) }) # define DWARF_VAL_LOC(c,v) DWARF_LOC ((v), DWARF_LOC_TYPE_VAL) # define DWARF_MEM_LOC(c,m) DWARF_LOC ((m), DWARF_LOC_TYPE_MEM) #ifdef UNW_LOCAL_ONLY # define DWARF_NULL_LOC DWARF_LOC (0, 0) # define DWARF_IS_NULL_LOC(l) (DWARF_GET_LOC (l) == 0) # define DWARF_REG_LOC(c,r) (DWARF_LOC((unw_word_t) \ x86_64_r_uc_addr(dwarf_get_uc(c), (r)), 0)) # define DWARF_FPREG_LOC(c,r) (DWARF_LOC((unw_word_t) \ x86_64_r_uc_addr(dwarf_get_uc(c), (r)), 0)) #else /* !UNW_LOCAL_ONLY */ # define DWARF_NULL_LOC DWARF_LOC (0, 0) static inline int dwarf_is_null_loc(dwarf_loc_t l) { return l.val == 0 && l.type == 0; } # define DWARF_IS_NULL_LOC(l) dwarf_is_null_loc(l) # define DWARF_REG_LOC(c,r) DWARF_LOC((r), DWARF_LOC_TYPE_REG) # define DWARF_FPREG_LOC(c,r) DWARF_LOC((r), (DWARF_LOC_TYPE_REG \ | DWARF_LOC_TYPE_FP)) #endif /* !UNW_LOCAL_ONLY */ static inline int dwarf_getfp (struct dwarf_cursor *c, dwarf_loc_t loc, unw_fpreg_t *val) { if (DWARF_IS_NULL_LOC (loc)) return -UNW_EBADREG; abort (); } static inline int dwarf_putfp (struct dwarf_cursor *c, dwarf_loc_t loc, unw_fpreg_t val) { if (DWARF_IS_NULL_LOC (loc)) return -UNW_EBADREG; abort (); } static inline int dwarf_get (struct dwarf_cursor *c, dwarf_loc_t loc, unw_word_t *val) { if (DWARF_IS_NULL_LOC (loc)) return -UNW_EBADREG; if (DWARF_IS_REG_LOC (loc)) return (*c->as->acc.access_reg) (c->as, DWARF_GET_LOC (loc), val, 0, c->as_arg); if (DWARF_IS_MEM_LOC (loc)) return (*c->as->acc.access_mem) (c->as, DWARF_GET_LOC (loc), val, 0, c->as_arg); assert(DWARF_IS_VAL_LOC (loc)); *val = DWARF_GET_LOC (loc); return 0; } static inline int dwarf_put (struct dwarf_cursor *c, dwarf_loc_t loc, unw_word_t val) { assert(!DWARF_IS_VAL_LOC (loc)); if (DWARF_IS_NULL_LOC (loc)) return -UNW_EBADREG; if (DWARF_IS_REG_LOC (loc)) return (*c->as->acc.access_reg) (c->as, DWARF_GET_LOC (loc), &val, 1, c->as_arg); else return (*c->as->acc.access_mem) (c->as, DWARF_GET_LOC (loc), &val, 1, c->as_arg); } #define tdep_getcontext_trace UNW_ARCH_OBJ(getcontext_trace) #define tdep_init_done UNW_OBJ(init_done) #define tdep_init_mem_validate UNW_OBJ(init_mem_validate) #define tdep_init UNW_OBJ(init) /* Platforms that support UNW_INFO_FORMAT_TABLE need to define tdep_search_unwind_table. */ #define tdep_search_unwind_table dwarf_search_unwind_table #define tdep_find_unwind_table dwarf_find_unwind_table #define tdep_get_elf_image UNW_ARCH_OBJ(get_elf_image) #define tdep_get_exe_image_path UNW_ARCH_OBJ(get_exe_image_path) #define tdep_access_reg UNW_OBJ(access_reg) #define tdep_access_fpreg UNW_OBJ(access_fpreg) #if __linux__ # define tdep_fetch_frame UNW_OBJ(fetch_frame) # define tdep_cache_frame UNW_OBJ(cache_frame) # define tdep_reuse_frame UNW_OBJ(reuse_frame) #else # define tdep_fetch_frame(c,ip,n) do {} while(0) # define tdep_cache_frame(c) 0 # define tdep_reuse_frame(c,frame) do {} while(0) #endif #define tdep_stash_frame UNW_OBJ(stash_frame) #define tdep_trace UNW_OBJ(tdep_trace) #define x86_64_r_uc_addr UNW_OBJ(r_uc_addr) #ifdef UNW_LOCAL_ONLY # define tdep_find_proc_info(c,ip,n) \ dwarf_find_proc_info((c)->as, (ip), &(c)->pi, (n), \ (c)->as_arg) # define tdep_put_unwind_info(as,pi,arg) \ dwarf_put_unwind_info((as), (pi), (arg)) #else # define tdep_find_proc_info(c,ip,n) \ (*(c)->as->acc.find_proc_info)((c)->as, (ip), &(c)->pi, (n), \ (c)->as_arg) # define tdep_put_unwind_info(as,pi,arg) \ (*(as)->acc.put_unwind_info)((as), (pi), (arg)) #endif #define tdep_get_as(c) ((c)->dwarf.as) #define tdep_get_as_arg(c) ((c)->dwarf.as_arg) #define tdep_get_ip(c) ((c)->dwarf.ip) #define tdep_big_endian(as) 0 extern atomic_bool tdep_init_done; extern void tdep_init (void); extern void tdep_init_mem_validate (void); extern int tdep_search_unwind_table (unw_addr_space_t as, unw_word_t ip, unw_dyn_info_t *di, unw_proc_info_t *pi, int need_unwind_info, void *arg); extern void *x86_64_r_uc_addr (ucontext_t *uc, int reg); extern int tdep_get_elf_image (struct elf_image *ei, pid_t pid, unw_word_t ip, unsigned long *segbase, unsigned long *mapoff, char *path, size_t pathlen); extern void tdep_get_exe_image_path (char *path); extern int tdep_access_reg (struct cursor *c, unw_regnum_t reg, unw_word_t *valp, int write); extern int tdep_access_fpreg (struct cursor *c, unw_regnum_t reg, unw_fpreg_t *valp, int write); #if __linux__ extern void tdep_fetch_frame (struct dwarf_cursor *c, unw_word_t ip, int need_unwind_info); extern int tdep_cache_frame (struct dwarf_cursor *c); extern void tdep_reuse_frame (struct dwarf_cursor *c, int frame); extern void tdep_stash_frame (struct dwarf_cursor *c, struct dwarf_reg_state *rs); #endif extern int tdep_getcontext_trace (unw_tdep_context_t *); extern int tdep_trace (unw_cursor_t *cursor, void **addresses, int *n); #endif /* X86_64_LIBUNWIND_I_H */
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/native/external/brotli/common/constants.h
/* Copyright 2016 Google Inc. All Rights Reserved. Distributed under MIT license. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT */ /** * @file * Common constants used in decoder and encoder API. */ #ifndef BROTLI_COMMON_CONSTANTS_H_ #define BROTLI_COMMON_CONSTANTS_H_ #include "./platform.h" #include <brotli/port.h> #include <brotli/types.h> /* Specification: 7.3. Encoding of the context map */ #define BROTLI_CONTEXT_MAP_MAX_RLE 16 /* Specification: 2. Compressed representation overview */ #define BROTLI_MAX_NUMBER_OF_BLOCK_TYPES 256 /* Specification: 3.3. Alphabet sizes: insert-and-copy length */ #define BROTLI_NUM_LITERAL_SYMBOLS 256 #define BROTLI_NUM_COMMAND_SYMBOLS 704 #define BROTLI_NUM_BLOCK_LEN_SYMBOLS 26 #define BROTLI_MAX_CONTEXT_MAP_SYMBOLS (BROTLI_MAX_NUMBER_OF_BLOCK_TYPES + \ BROTLI_CONTEXT_MAP_MAX_RLE) #define BROTLI_MAX_BLOCK_TYPE_SYMBOLS (BROTLI_MAX_NUMBER_OF_BLOCK_TYPES + 2) /* Specification: 3.5. Complex prefix codes */ #define BROTLI_REPEAT_PREVIOUS_CODE_LENGTH 16 #define BROTLI_REPEAT_ZERO_CODE_LENGTH 17 #define BROTLI_CODE_LENGTH_CODES (BROTLI_REPEAT_ZERO_CODE_LENGTH + 1) /* "code length of 8 is repeated" */ #define BROTLI_INITIAL_REPEATED_CODE_LENGTH 8 /* "Large Window Brotli" */ /** * The theoretical maximum number of distance bits specified for large window * brotli, for 64-bit encoders and decoders. Even when in practice 32-bit * encoders and decoders only support up to 30 max distance bits, the value is * set to 62 because it affects the large window brotli file format. * Specifically, it affects the encoding of simple huffman tree for distances, * see Specification RFC 7932 chapter 3.4. */ #define BROTLI_LARGE_MAX_DISTANCE_BITS 62U #define BROTLI_LARGE_MIN_WBITS 10 /** * The maximum supported large brotli window bits by the encoder and decoder. * Large window brotli allows up to 62 bits, however the current encoder and * decoder, designed for 32-bit integers, only support up to 30 bits maximum. */ #define BROTLI_LARGE_MAX_WBITS 30 /* Specification: 4. Encoding of distances */ #define BROTLI_NUM_DISTANCE_SHORT_CODES 16 /** * Maximal number of "postfix" bits. * * Number of "postfix" bits is stored as 2 bits in meta-block header. */ #define BROTLI_MAX_NPOSTFIX 3 #define BROTLI_MAX_NDIRECT 120 #define BROTLI_MAX_DISTANCE_BITS 24U #define BROTLI_DISTANCE_ALPHABET_SIZE(NPOSTFIX, NDIRECT, MAXNBITS) ( \ BROTLI_NUM_DISTANCE_SHORT_CODES + (NDIRECT) + \ ((MAXNBITS) << ((NPOSTFIX) + 1))) /* BROTLI_NUM_DISTANCE_SYMBOLS == 1128 */ #define BROTLI_NUM_DISTANCE_SYMBOLS \ BROTLI_DISTANCE_ALPHABET_SIZE( \ BROTLI_MAX_NDIRECT, BROTLI_MAX_NPOSTFIX, BROTLI_LARGE_MAX_DISTANCE_BITS) /* ((1 << 26) - 4) is the maximal distance that can be expressed in RFC 7932 brotli stream using NPOSTFIX = 0 and NDIRECT = 0. With other NPOSTFIX and NDIRECT values distances up to ((1 << 29) + 88) could be expressed. */ #define BROTLI_MAX_DISTANCE 0x3FFFFFC /* ((1 << 31) - 4) is the safe distance limit. Using this number as a limit allows safe distance calculation without overflows, given the distance alphabet size is limited to corresponding size (see kLargeWindowDistanceCodeLimits). */ #define BROTLI_MAX_ALLOWED_DISTANCE 0x7FFFFFFC /* Specification: 4. Encoding of Literal Insertion Lengths and Copy Lengths */ #define BROTLI_NUM_INS_COPY_CODES 24 /* 7.1. Context modes and context ID lookup for literals */ /* "context IDs for literals are in the range of 0..63" */ #define BROTLI_LITERAL_CONTEXT_BITS 6 /* 7.2. Context ID for distances */ #define BROTLI_DISTANCE_CONTEXT_BITS 2 /* 9.1. Format of the Stream Header */ /* Number of slack bytes for window size. Don't confuse with BROTLI_NUM_DISTANCE_SHORT_CODES. */ #define BROTLI_WINDOW_GAP 16 #define BROTLI_MAX_BACKWARD_LIMIT(W) (((size_t)1 << (W)) - BROTLI_WINDOW_GAP) typedef struct BrotliDistanceCodeLimit { uint32_t max_alphabet_size; uint32_t max_distance; } BrotliDistanceCodeLimit; /* This function calculates maximal size of distance alphabet, such that the distances greater than the given values can not be represented. This limits are designed to support fast and safe 32-bit decoders. "32-bit" means that signed integer values up to ((1 << 31) - 1) could be safely expressed. Brotli distance alphabet symbols do not represent consecutive distance ranges. Each distance alphabet symbol (excluding direct distances and short codes), represent interleaved (for NPOSTFIX > 0) range of distances. A "group" of consecutive (1 << NPOSTFIX) symbols represent non-interleaved range. Two consecutive groups require the same amount of "extra bits". It is important that distance alphabet represents complete "groups". To avoid complex logic on encoder side about interleaved ranges it was decided to restrict both sides to complete distance code "groups". */ BROTLI_UNUSED_FUNCTION BrotliDistanceCodeLimit BrotliCalculateDistanceCodeLimit( uint32_t max_distance, uint32_t npostfix, uint32_t ndirect) { BrotliDistanceCodeLimit result; /* Marking this function as unused, because not all files including "constants.h" use it -> compiler warns about that. */ BROTLI_UNUSED(&BrotliCalculateDistanceCodeLimit); if (max_distance <= ndirect) { /* This case never happens / exists only for the sake of completeness. */ result.max_alphabet_size = max_distance + BROTLI_NUM_DISTANCE_SHORT_CODES; result.max_distance = max_distance; return result; } else { /* The first prohibited value. */ uint32_t forbidden_distance = max_distance + 1; /* Subtract "directly" encoded region. */ uint32_t offset = forbidden_distance - ndirect - 1; uint32_t ndistbits = 0; uint32_t tmp; uint32_t half; uint32_t group; /* Postfix for the last dcode in the group. */ uint32_t postfix = (1u << npostfix) - 1; uint32_t extra; uint32_t start; /* Remove postfix and "head-start". */ offset = (offset >> npostfix) + 4; /* Calculate the number of distance bits. */ tmp = offset / 2; /* Poor-man's log2floor, to avoid extra dependencies. */ while (tmp != 0) {ndistbits++; tmp = tmp >> 1;} /* One bit is covered with subrange addressing ("half"). */ ndistbits--; /* Find subrange. */ half = (offset >> ndistbits) & 1; /* Calculate the "group" part of dcode. */ group = ((ndistbits - 1) << 1) | half; /* Calculated "group" covers the prohibited distance value. */ if (group == 0) { /* This case is added for correctness; does not occur for limit > 128. */ result.max_alphabet_size = ndirect + BROTLI_NUM_DISTANCE_SHORT_CODES; result.max_distance = ndirect; return result; } /* Decrement "group", so it is the last permitted "group". */ group--; /* After group was decremented, ndistbits and half must be recalculated. */ ndistbits = (group >> 1) + 1; /* The last available distance in the subrange has all extra bits set. */ extra = (1u << ndistbits) - 1; /* Calculate region start. NB: ndistbits >= 1. */ start = (1u << (ndistbits + 1)) - 4; /* Move to subregion. */ start += (group & 1) << ndistbits; /* Calculate the alphabet size. */ result.max_alphabet_size = ((group << npostfix) | postfix) + ndirect + BROTLI_NUM_DISTANCE_SHORT_CODES + 1; /* Calculate the maximal distance representable by alphabet. */ result.max_distance = ((start + extra) << npostfix) + postfix + ndirect + 1; return result; } } /* Represents the range of values belonging to a prefix code: [offset, offset + 2^nbits) */ typedef struct { uint16_t offset; uint8_t nbits; } BrotliPrefixCodeRange; /* "Soft-private", it is exported, but not "advertised" as API. */ BROTLI_COMMON_API extern const BrotliPrefixCodeRange _kBrotliPrefixCodeRanges[BROTLI_NUM_BLOCK_LEN_SYMBOLS]; #endif /* BROTLI_COMMON_CONSTANTS_H_ */
/* Copyright 2016 Google Inc. All Rights Reserved. Distributed under MIT license. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT */ /** * @file * Common constants used in decoder and encoder API. */ #ifndef BROTLI_COMMON_CONSTANTS_H_ #define BROTLI_COMMON_CONSTANTS_H_ #include "./platform.h" #include <brotli/port.h> #include <brotli/types.h> /* Specification: 7.3. Encoding of the context map */ #define BROTLI_CONTEXT_MAP_MAX_RLE 16 /* Specification: 2. Compressed representation overview */ #define BROTLI_MAX_NUMBER_OF_BLOCK_TYPES 256 /* Specification: 3.3. Alphabet sizes: insert-and-copy length */ #define BROTLI_NUM_LITERAL_SYMBOLS 256 #define BROTLI_NUM_COMMAND_SYMBOLS 704 #define BROTLI_NUM_BLOCK_LEN_SYMBOLS 26 #define BROTLI_MAX_CONTEXT_MAP_SYMBOLS (BROTLI_MAX_NUMBER_OF_BLOCK_TYPES + \ BROTLI_CONTEXT_MAP_MAX_RLE) #define BROTLI_MAX_BLOCK_TYPE_SYMBOLS (BROTLI_MAX_NUMBER_OF_BLOCK_TYPES + 2) /* Specification: 3.5. Complex prefix codes */ #define BROTLI_REPEAT_PREVIOUS_CODE_LENGTH 16 #define BROTLI_REPEAT_ZERO_CODE_LENGTH 17 #define BROTLI_CODE_LENGTH_CODES (BROTLI_REPEAT_ZERO_CODE_LENGTH + 1) /* "code length of 8 is repeated" */ #define BROTLI_INITIAL_REPEATED_CODE_LENGTH 8 /* "Large Window Brotli" */ /** * The theoretical maximum number of distance bits specified for large window * brotli, for 64-bit encoders and decoders. Even when in practice 32-bit * encoders and decoders only support up to 30 max distance bits, the value is * set to 62 because it affects the large window brotli file format. * Specifically, it affects the encoding of simple huffman tree for distances, * see Specification RFC 7932 chapter 3.4. */ #define BROTLI_LARGE_MAX_DISTANCE_BITS 62U #define BROTLI_LARGE_MIN_WBITS 10 /** * The maximum supported large brotli window bits by the encoder and decoder. * Large window brotli allows up to 62 bits, however the current encoder and * decoder, designed for 32-bit integers, only support up to 30 bits maximum. */ #define BROTLI_LARGE_MAX_WBITS 30 /* Specification: 4. Encoding of distances */ #define BROTLI_NUM_DISTANCE_SHORT_CODES 16 /** * Maximal number of "postfix" bits. * * Number of "postfix" bits is stored as 2 bits in meta-block header. */ #define BROTLI_MAX_NPOSTFIX 3 #define BROTLI_MAX_NDIRECT 120 #define BROTLI_MAX_DISTANCE_BITS 24U #define BROTLI_DISTANCE_ALPHABET_SIZE(NPOSTFIX, NDIRECT, MAXNBITS) ( \ BROTLI_NUM_DISTANCE_SHORT_CODES + (NDIRECT) + \ ((MAXNBITS) << ((NPOSTFIX) + 1))) /* BROTLI_NUM_DISTANCE_SYMBOLS == 1128 */ #define BROTLI_NUM_DISTANCE_SYMBOLS \ BROTLI_DISTANCE_ALPHABET_SIZE( \ BROTLI_MAX_NDIRECT, BROTLI_MAX_NPOSTFIX, BROTLI_LARGE_MAX_DISTANCE_BITS) /* ((1 << 26) - 4) is the maximal distance that can be expressed in RFC 7932 brotli stream using NPOSTFIX = 0 and NDIRECT = 0. With other NPOSTFIX and NDIRECT values distances up to ((1 << 29) + 88) could be expressed. */ #define BROTLI_MAX_DISTANCE 0x3FFFFFC /* ((1 << 31) - 4) is the safe distance limit. Using this number as a limit allows safe distance calculation without overflows, given the distance alphabet size is limited to corresponding size (see kLargeWindowDistanceCodeLimits). */ #define BROTLI_MAX_ALLOWED_DISTANCE 0x7FFFFFFC /* Specification: 4. Encoding of Literal Insertion Lengths and Copy Lengths */ #define BROTLI_NUM_INS_COPY_CODES 24 /* 7.1. Context modes and context ID lookup for literals */ /* "context IDs for literals are in the range of 0..63" */ #define BROTLI_LITERAL_CONTEXT_BITS 6 /* 7.2. Context ID for distances */ #define BROTLI_DISTANCE_CONTEXT_BITS 2 /* 9.1. Format of the Stream Header */ /* Number of slack bytes for window size. Don't confuse with BROTLI_NUM_DISTANCE_SHORT_CODES. */ #define BROTLI_WINDOW_GAP 16 #define BROTLI_MAX_BACKWARD_LIMIT(W) (((size_t)1 << (W)) - BROTLI_WINDOW_GAP) typedef struct BrotliDistanceCodeLimit { uint32_t max_alphabet_size; uint32_t max_distance; } BrotliDistanceCodeLimit; /* This function calculates maximal size of distance alphabet, such that the distances greater than the given values can not be represented. This limits are designed to support fast and safe 32-bit decoders. "32-bit" means that signed integer values up to ((1 << 31) - 1) could be safely expressed. Brotli distance alphabet symbols do not represent consecutive distance ranges. Each distance alphabet symbol (excluding direct distances and short codes), represent interleaved (for NPOSTFIX > 0) range of distances. A "group" of consecutive (1 << NPOSTFIX) symbols represent non-interleaved range. Two consecutive groups require the same amount of "extra bits". It is important that distance alphabet represents complete "groups". To avoid complex logic on encoder side about interleaved ranges it was decided to restrict both sides to complete distance code "groups". */ BROTLI_UNUSED_FUNCTION BrotliDistanceCodeLimit BrotliCalculateDistanceCodeLimit( uint32_t max_distance, uint32_t npostfix, uint32_t ndirect) { BrotliDistanceCodeLimit result; /* Marking this function as unused, because not all files including "constants.h" use it -> compiler warns about that. */ BROTLI_UNUSED(&BrotliCalculateDistanceCodeLimit); if (max_distance <= ndirect) { /* This case never happens / exists only for the sake of completeness. */ result.max_alphabet_size = max_distance + BROTLI_NUM_DISTANCE_SHORT_CODES; result.max_distance = max_distance; return result; } else { /* The first prohibited value. */ uint32_t forbidden_distance = max_distance + 1; /* Subtract "directly" encoded region. */ uint32_t offset = forbidden_distance - ndirect - 1; uint32_t ndistbits = 0; uint32_t tmp; uint32_t half; uint32_t group; /* Postfix for the last dcode in the group. */ uint32_t postfix = (1u << npostfix) - 1; uint32_t extra; uint32_t start; /* Remove postfix and "head-start". */ offset = (offset >> npostfix) + 4; /* Calculate the number of distance bits. */ tmp = offset / 2; /* Poor-man's log2floor, to avoid extra dependencies. */ while (tmp != 0) {ndistbits++; tmp = tmp >> 1;} /* One bit is covered with subrange addressing ("half"). */ ndistbits--; /* Find subrange. */ half = (offset >> ndistbits) & 1; /* Calculate the "group" part of dcode. */ group = ((ndistbits - 1) << 1) | half; /* Calculated "group" covers the prohibited distance value. */ if (group == 0) { /* This case is added for correctness; does not occur for limit > 128. */ result.max_alphabet_size = ndirect + BROTLI_NUM_DISTANCE_SHORT_CODES; result.max_distance = ndirect; return result; } /* Decrement "group", so it is the last permitted "group". */ group--; /* After group was decremented, ndistbits and half must be recalculated. */ ndistbits = (group >> 1) + 1; /* The last available distance in the subrange has all extra bits set. */ extra = (1u << ndistbits) - 1; /* Calculate region start. NB: ndistbits >= 1. */ start = (1u << (ndistbits + 1)) - 4; /* Move to subregion. */ start += (group & 1) << ndistbits; /* Calculate the alphabet size. */ result.max_alphabet_size = ((group << npostfix) | postfix) + ndirect + BROTLI_NUM_DISTANCE_SHORT_CODES + 1; /* Calculate the maximal distance representable by alphabet. */ result.max_distance = ((start + extra) << npostfix) + postfix + ndirect + 1; return result; } } /* Represents the range of values belonging to a prefix code: [offset, offset + 2^nbits) */ typedef struct { uint16_t offset; uint8_t nbits; } BrotliPrefixCodeRange; /* "Soft-private", it is exported, but not "advertised" as API. */ BROTLI_COMMON_API extern const BrotliPrefixCodeRange _kBrotliPrefixCodeRanges[BROTLI_NUM_BLOCK_LEN_SYMBOLS]; #endif /* BROTLI_COMMON_CONSTANTS_H_ */
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/native/libs/System.Security.Cryptography.Native/pal_x509_root.c
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "pal_types.h" #include "pal_x509_root.h" #include <assert.h> const char* CryptoNative_GetX509RootStorePath(uint8_t* defaultPath) { assert(defaultPath != NULL); // No error queue impact. const char* dir = getenv(X509_get_default_cert_dir_env()); *defaultPath = 0; if (!dir) { dir = X509_get_default_cert_dir(); *defaultPath = 1; } return dir; } const char* CryptoNative_GetX509RootStoreFile(uint8_t* defaultPath) { assert(defaultPath != NULL); // No error queue impact. const char* file = getenv(X509_get_default_cert_file_env()); *defaultPath = 0; if (!file) { file = X509_get_default_cert_file(); *defaultPath = 1; } return file; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "pal_types.h" #include "pal_x509_root.h" #include <assert.h> const char* CryptoNative_GetX509RootStorePath(uint8_t* defaultPath) { assert(defaultPath != NULL); // No error queue impact. const char* dir = getenv(X509_get_default_cert_dir_env()); *defaultPath = 0; if (!dir) { dir = X509_get_default_cert_dir(); *defaultPath = 1; } return dir; } const char* CryptoNative_GetX509RootStoreFile(uint8_t* defaultPath) { assert(defaultPath != NULL); // No error queue impact. const char* file = getenv(X509_get_default_cert_file_env()); *defaultPath = 0; if (!file) { file = X509_get_default_cert_file(); *defaultPath = 1; } return file; }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/pal/src/libunwind/tests/Lia64-test-readonly.c
#define UNW_LOCAL_ONLY #include <libunwind.h> #if !defined(UNW_REMOTE_ONLY) #include "Gia64-test-readonly.c" #endif
#define UNW_LOCAL_ONLY #include <libunwind.h> #if !defined(UNW_REMOTE_ONLY) #include "Gia64-test-readonly.c" #endif
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/pal/src/libunwind/src/mi/Gdyn-remote.c
/* libunwind - a platform-independent unwind library Copyright (C) 2001-2002, 2005 Hewlett-Packard Co Contributed by David Mosberger-Tang <[email protected]> This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdlib.h> #include "libunwind_i.h" #include "remote.h" static void free_regions (unw_dyn_region_info_t *region) { if (region->next) free_regions (region->next); free (region); } static int intern_op (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr, unw_dyn_op_t *op, void *arg) { int ret; if ((ret = fetch8 (as, a, addr, &op->tag, arg)) < 0 || (ret = fetch8 (as, a, addr, &op->qp, arg)) < 0 || (ret = fetch16 (as, a, addr, &op->reg, arg)) < 0 || (ret = fetch32 (as, a, addr, &op->when, arg)) < 0 || (ret = fetchw (as, a, addr, &op->val, arg)) < 0) return ret; return 0; } static int intern_regions (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr, unw_dyn_region_info_t **regionp, void *arg) { uint32_t insn_count, op_count, i; unw_dyn_region_info_t *region; unw_word_t next_addr; int ret; *regionp = NULL; if (!*addr) return 0; /* NULL region-list */ if ((ret = fetchw (as, a, addr, &next_addr, arg)) < 0 || (ret = fetch32 (as, a, addr, (int32_t *) &insn_count, arg)) < 0 || (ret = fetch32 (as, a, addr, (int32_t *) &op_count, arg)) < 0) return ret; region = calloc (1, _U_dyn_region_info_size (op_count)); if (!region) { ret = -UNW_ENOMEM; goto out; } region->insn_count = insn_count; region->op_count = op_count; for (i = 0; i < op_count; ++i) if ((ret = intern_op (as, a, addr, region->op + i, arg)) < 0) goto out; if (next_addr) if ((ret = intern_regions (as, a, &next_addr, &region->next, arg)) < 0) goto out; *regionp = region; return 0; out: if (region) free_regions (region); return ret; } static int intern_array (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr, unw_word_t table_len, unw_word_t **table_data, void *arg) { unw_word_t i, *data = calloc (table_len, WSIZE); int ret = 0; if (!data) { ret = -UNW_ENOMEM; goto out; } for (i = 0; i < table_len; ++i) if (fetchw (as, a, addr, data + i, arg) < 0) goto out; *table_data = data; return 0; out: if (data) free (data); return ret; } static void free_dyn_info (unw_dyn_info_t *di) { switch (di->format) { case UNW_INFO_FORMAT_DYNAMIC: if (di->u.pi.regions) { free_regions (di->u.pi.regions); di->u.pi.regions = NULL; } break; case UNW_INFO_FORMAT_TABLE: if (di->u.ti.table_data) { free (di->u.ti.table_data); di->u.ti.table_data = NULL; } break; case UNW_INFO_FORMAT_REMOTE_TABLE: default: break; } } static int intern_dyn_info (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr, unw_dyn_info_t *di, void *arg) { unw_word_t first_region; int ret; switch (di->format) { case UNW_INFO_FORMAT_DYNAMIC: if ((ret = fetchw (as, a, addr, &di->u.pi.name_ptr, arg)) < 0 || (ret = fetchw (as, a, addr, &di->u.pi.handler, arg)) < 0 || (ret = fetch32 (as, a, addr, (int32_t *) &di->u.pi.flags, arg)) < 0) goto out; *addr += 4; /* skip over pad0 */ if ((ret = fetchw (as, a, addr, &first_region, arg)) < 0 || (ret = intern_regions (as, a, &first_region, &di->u.pi.regions, arg)) < 0) goto out; break; case UNW_INFO_FORMAT_TABLE: if ((ret = fetchw (as, a, addr, &di->u.ti.name_ptr, arg)) < 0 || (ret = fetchw (as, a, addr, &di->u.ti.segbase, arg)) < 0 || (ret = fetchw (as, a, addr, &di->u.ti.table_len, arg)) < 0 || (ret = intern_array (as, a, addr, di->u.ti.table_len, &di->u.ti.table_data, arg)) < 0) goto out; break; case UNW_INFO_FORMAT_REMOTE_TABLE: if ((ret = fetchw (as, a, addr, &di->u.rti.name_ptr, arg)) < 0 || (ret = fetchw (as, a, addr, &di->u.rti.segbase, arg)) < 0 || (ret = fetchw (as, a, addr, &di->u.rti.table_len, arg)) < 0 || (ret = fetchw (as, a, addr, &di->u.rti.table_data, arg)) < 0) goto out; break; default: ret = -UNW_ENOINFO; goto out; } return 0; out: free_dyn_info (di); return ret; } HIDDEN int unwi_dyn_remote_find_proc_info (unw_addr_space_t as, unw_word_t ip, unw_proc_info_t *pi, int need_unwind_info, void *arg) { unw_accessors_t *a = unw_get_accessors_int (as); unw_word_t dyn_list_addr, addr, next_addr, gen1, gen2, start_ip, end_ip; unw_dyn_info_t *di = NULL; int ret; if (as->dyn_info_list_addr) dyn_list_addr = as->dyn_info_list_addr; else { if ((*a->get_dyn_info_list_addr) (as, &dyn_list_addr, arg) < 0) return -UNW_ENOINFO; if (as->caching_policy != UNW_CACHE_NONE) as->dyn_info_list_addr = dyn_list_addr; } do { addr = dyn_list_addr; ret = -UNW_ENOINFO; if (fetchw (as, a, &addr, &gen1, arg) < 0 || fetchw (as, a, &addr, &next_addr, arg) < 0) return ret; for (addr = next_addr; addr != 0; addr = next_addr) { if (fetchw (as, a, &addr, &next_addr, arg) < 0) goto recheck; /* only fail if generation # didn't change */ addr += WSIZE; /* skip over prev_addr */ if (fetchw (as, a, &addr, &start_ip, arg) < 0 || fetchw (as, a, &addr, &end_ip, arg) < 0) goto recheck; /* only fail if generation # didn't change */ if (ip >= start_ip && ip < end_ip) { if (!di) di = calloc (1, sizeof (*di)); di->start_ip = start_ip; di->end_ip = end_ip; if (fetchw (as, a, &addr, &di->gp, arg) < 0 || fetch32 (as, a, &addr, &di->format, arg) < 0) goto recheck; /* only fail if generation # didn't change */ addr += 4; /* skip over padding */ if (need_unwind_info && intern_dyn_info (as, a, &addr, di, arg) < 0) goto recheck; /* only fail if generation # didn't change */ if (unwi_extract_dynamic_proc_info (as, ip, pi, di, need_unwind_info, arg) < 0) { free_dyn_info (di); goto recheck; /* only fail if generation # didn't change */ } ret = 0; /* OK, found it */ break; } } /* Re-check generation number to ensure the data we have is consistent. */ recheck: addr = dyn_list_addr; if (fetchw (as, a, &addr, &gen2, arg) < 0) return ret; } while (gen1 != gen2); if (ret < 0 && di) free (di); return ret; } HIDDEN void unwi_dyn_remote_put_unwind_info (unw_addr_space_t as, unw_proc_info_t *pi, void *arg) { if (!pi->unwind_info) return; free_dyn_info (pi->unwind_info); free (pi->unwind_info); pi->unwind_info = NULL; } /* Returns 1 if the cache is up-to-date or -1 if the cache contained stale data and had to be flushed. */ HIDDEN int unwi_dyn_validate_cache (unw_addr_space_t as, void *arg) { unw_word_t addr, gen; unw_accessors_t *a; if (!as->dyn_info_list_addr) /* If we don't have the dyn_info_list_addr, we don't have anything in the cache. */ return 0; a = unw_get_accessors_int (as); addr = as->dyn_info_list_addr; if (fetchw (as, a, &addr, &gen, arg) < 0) return 1; if (gen == as->dyn_generation) return 1; unw_flush_cache (as, 0, 0); as->dyn_generation = gen; return -1; }
/* libunwind - a platform-independent unwind library Copyright (C) 2001-2002, 2005 Hewlett-Packard Co Contributed by David Mosberger-Tang <[email protected]> This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdlib.h> #include "libunwind_i.h" #include "remote.h" static void free_regions (unw_dyn_region_info_t *region) { if (region->next) free_regions (region->next); free (region); } static int intern_op (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr, unw_dyn_op_t *op, void *arg) { int ret; if ((ret = fetch8 (as, a, addr, &op->tag, arg)) < 0 || (ret = fetch8 (as, a, addr, &op->qp, arg)) < 0 || (ret = fetch16 (as, a, addr, &op->reg, arg)) < 0 || (ret = fetch32 (as, a, addr, &op->when, arg)) < 0 || (ret = fetchw (as, a, addr, &op->val, arg)) < 0) return ret; return 0; } static int intern_regions (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr, unw_dyn_region_info_t **regionp, void *arg) { uint32_t insn_count, op_count, i; unw_dyn_region_info_t *region; unw_word_t next_addr; int ret; *regionp = NULL; if (!*addr) return 0; /* NULL region-list */ if ((ret = fetchw (as, a, addr, &next_addr, arg)) < 0 || (ret = fetch32 (as, a, addr, (int32_t *) &insn_count, arg)) < 0 || (ret = fetch32 (as, a, addr, (int32_t *) &op_count, arg)) < 0) return ret; region = calloc (1, _U_dyn_region_info_size (op_count)); if (!region) { ret = -UNW_ENOMEM; goto out; } region->insn_count = insn_count; region->op_count = op_count; for (i = 0; i < op_count; ++i) if ((ret = intern_op (as, a, addr, region->op + i, arg)) < 0) goto out; if (next_addr) if ((ret = intern_regions (as, a, &next_addr, &region->next, arg)) < 0) goto out; *regionp = region; return 0; out: if (region) free_regions (region); return ret; } static int intern_array (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr, unw_word_t table_len, unw_word_t **table_data, void *arg) { unw_word_t i, *data = calloc (table_len, WSIZE); int ret = 0; if (!data) { ret = -UNW_ENOMEM; goto out; } for (i = 0; i < table_len; ++i) if (fetchw (as, a, addr, data + i, arg) < 0) goto out; *table_data = data; return 0; out: if (data) free (data); return ret; } static void free_dyn_info (unw_dyn_info_t *di) { switch (di->format) { case UNW_INFO_FORMAT_DYNAMIC: if (di->u.pi.regions) { free_regions (di->u.pi.regions); di->u.pi.regions = NULL; } break; case UNW_INFO_FORMAT_TABLE: if (di->u.ti.table_data) { free (di->u.ti.table_data); di->u.ti.table_data = NULL; } break; case UNW_INFO_FORMAT_REMOTE_TABLE: default: break; } } static int intern_dyn_info (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr, unw_dyn_info_t *di, void *arg) { unw_word_t first_region; int ret; switch (di->format) { case UNW_INFO_FORMAT_DYNAMIC: if ((ret = fetchw (as, a, addr, &di->u.pi.name_ptr, arg)) < 0 || (ret = fetchw (as, a, addr, &di->u.pi.handler, arg)) < 0 || (ret = fetch32 (as, a, addr, (int32_t *) &di->u.pi.flags, arg)) < 0) goto out; *addr += 4; /* skip over pad0 */ if ((ret = fetchw (as, a, addr, &first_region, arg)) < 0 || (ret = intern_regions (as, a, &first_region, &di->u.pi.regions, arg)) < 0) goto out; break; case UNW_INFO_FORMAT_TABLE: if ((ret = fetchw (as, a, addr, &di->u.ti.name_ptr, arg)) < 0 || (ret = fetchw (as, a, addr, &di->u.ti.segbase, arg)) < 0 || (ret = fetchw (as, a, addr, &di->u.ti.table_len, arg)) < 0 || (ret = intern_array (as, a, addr, di->u.ti.table_len, &di->u.ti.table_data, arg)) < 0) goto out; break; case UNW_INFO_FORMAT_REMOTE_TABLE: if ((ret = fetchw (as, a, addr, &di->u.rti.name_ptr, arg)) < 0 || (ret = fetchw (as, a, addr, &di->u.rti.segbase, arg)) < 0 || (ret = fetchw (as, a, addr, &di->u.rti.table_len, arg)) < 0 || (ret = fetchw (as, a, addr, &di->u.rti.table_data, arg)) < 0) goto out; break; default: ret = -UNW_ENOINFO; goto out; } return 0; out: free_dyn_info (di); return ret; } HIDDEN int unwi_dyn_remote_find_proc_info (unw_addr_space_t as, unw_word_t ip, unw_proc_info_t *pi, int need_unwind_info, void *arg) { unw_accessors_t *a = unw_get_accessors_int (as); unw_word_t dyn_list_addr, addr, next_addr, gen1, gen2, start_ip, end_ip; unw_dyn_info_t *di = NULL; int ret; if (as->dyn_info_list_addr) dyn_list_addr = as->dyn_info_list_addr; else { if ((*a->get_dyn_info_list_addr) (as, &dyn_list_addr, arg) < 0) return -UNW_ENOINFO; if (as->caching_policy != UNW_CACHE_NONE) as->dyn_info_list_addr = dyn_list_addr; } do { addr = dyn_list_addr; ret = -UNW_ENOINFO; if (fetchw (as, a, &addr, &gen1, arg) < 0 || fetchw (as, a, &addr, &next_addr, arg) < 0) return ret; for (addr = next_addr; addr != 0; addr = next_addr) { if (fetchw (as, a, &addr, &next_addr, arg) < 0) goto recheck; /* only fail if generation # didn't change */ addr += WSIZE; /* skip over prev_addr */ if (fetchw (as, a, &addr, &start_ip, arg) < 0 || fetchw (as, a, &addr, &end_ip, arg) < 0) goto recheck; /* only fail if generation # didn't change */ if (ip >= start_ip && ip < end_ip) { if (!di) di = calloc (1, sizeof (*di)); di->start_ip = start_ip; di->end_ip = end_ip; if (fetchw (as, a, &addr, &di->gp, arg) < 0 || fetch32 (as, a, &addr, &di->format, arg) < 0) goto recheck; /* only fail if generation # didn't change */ addr += 4; /* skip over padding */ if (need_unwind_info && intern_dyn_info (as, a, &addr, di, arg) < 0) goto recheck; /* only fail if generation # didn't change */ if (unwi_extract_dynamic_proc_info (as, ip, pi, di, need_unwind_info, arg) < 0) { free_dyn_info (di); goto recheck; /* only fail if generation # didn't change */ } ret = 0; /* OK, found it */ break; } } /* Re-check generation number to ensure the data we have is consistent. */ recheck: addr = dyn_list_addr; if (fetchw (as, a, &addr, &gen2, arg) < 0) return ret; } while (gen1 != gen2); if (ret < 0 && di) free (di); return ret; } HIDDEN void unwi_dyn_remote_put_unwind_info (unw_addr_space_t as, unw_proc_info_t *pi, void *arg) { if (!pi->unwind_info) return; free_dyn_info (pi->unwind_info); free (pi->unwind_info); pi->unwind_info = NULL; } /* Returns 1 if the cache is up-to-date or -1 if the cache contained stale data and had to be flushed. */ HIDDEN int unwi_dyn_validate_cache (unw_addr_space_t as, void *arg) { unw_word_t addr, gen; unw_accessors_t *a; if (!as->dyn_info_list_addr) /* If we don't have the dyn_info_list_addr, we don't have anything in the cache. */ return 0; a = unw_get_accessors_int (as); addr = as->dyn_info_list_addr; if (fetchw (as, a, &addr, &gen, arg) < 0) return 1; if (gen == as->dyn_generation) return 1; unw_flush_cache (as, 0, 0); as->dyn_generation = gen; return -1; }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/tests/profiler/native/inlining/inlining.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #pragma once #include "../profiler.h" #include <memory> class InliningProfiler : public Profiler { public: static std::shared_ptr<InliningProfiler> s_profiler; InliningProfiler() : Profiler(), _failures(0), _inInlining(false), _inBlockInlining(false), _inNoResponse(false) { } static GUID GetClsid(); virtual HRESULT STDMETHODCALLTYPE Initialize(IUnknown* pICorProfilerInfoUnk); virtual HRESULT STDMETHODCALLTYPE Shutdown(); virtual HRESULT STDMETHODCALLTYPE JITInlining(FunctionID callerId, FunctionID calleeId, BOOL* pfShouldInline); HRESULT STDMETHODCALLTYPE EnterCallback(FunctionIDOrClientID functionId, COR_PRF_ELT_INFO eltInfo); HRESULT STDMETHODCALLTYPE LeaveCallback(FunctionIDOrClientID functionId, COR_PRF_ELT_INFO eltInfo); HRESULT STDMETHODCALLTYPE TailcallCallback(FunctionIDOrClientID functionId, COR_PRF_ELT_INFO eltInfo); private: std::atomic<int> _failures; bool _inInlining; bool _inBlockInlining; bool _inNoResponse; bool _sawInlineeCall; };
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #pragma once #include "../profiler.h" #include <memory> class InliningProfiler : public Profiler { public: static std::shared_ptr<InliningProfiler> s_profiler; InliningProfiler() : Profiler(), _failures(0), _inInlining(false), _inBlockInlining(false), _inNoResponse(false) { } static GUID GetClsid(); virtual HRESULT STDMETHODCALLTYPE Initialize(IUnknown* pICorProfilerInfoUnk); virtual HRESULT STDMETHODCALLTYPE Shutdown(); virtual HRESULT STDMETHODCALLTYPE JITInlining(FunctionID callerId, FunctionID calleeId, BOOL* pfShouldInline); HRESULT STDMETHODCALLTYPE EnterCallback(FunctionIDOrClientID functionId, COR_PRF_ELT_INFO eltInfo); HRESULT STDMETHODCALLTYPE LeaveCallback(FunctionIDOrClientID functionId, COR_PRF_ELT_INFO eltInfo); HRESULT STDMETHODCALLTYPE TailcallCallback(FunctionIDOrClientID functionId, COR_PRF_ELT_INFO eltInfo); private: std::atomic<int> _failures; bool _inInlining; bool _inBlockInlining; bool _inNoResponse; bool _sawInlineeCall; };
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/vm/castcache.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // File: castcache.h // #ifndef _CAST_CACHE_H #define _CAST_CACHE_H #include "util.hpp" // // A very lightweight cache that maps {source, target} -> result, where result is // a boolean value indicating that the type of the source can cast to the target type or // definitely cannot. // // In the terminology of ECMA335 the relationship is called "compatible-with". // This is the relation used by castclass and isinst (III.4.3). // // We generically allow either MethodTable* or TypeHandle as source/target. Either value // uniquely maps to a single type with no possibility of confusion. Besides for most types // TypeHandle a MethodTable* are the same value anyways. // // One thing to consider is that cast analysis is relatively fast, which demands that the cache is fast too. // On the other hand, we do not need to be 100% accurate about a presence of an entry in a cache, // since everything can be re-computed relatively quickly. // We still hope to have a good hit rate, but can tolerate items pushed/flushed from the cache. // // The overal design of the cache is an open-addressing hash table with quadratic probing // strategy and a limited bucket size. // In a case of inserting we - // 1) use an empty entry within the bucket path or preempt an entry with a longer distance from it origin. // 2) pick a random victim entry within the bucket and replace it with a new entry. // That is basically our expiration policy. We want to keep things simple. // // The cache permits fully concurrent writes and stores. We use versioned entries to detect incomplete states and // tearing, which happens temporarily during updating. Entries in an inconsistent state are ignored by readers and writers. // As a result TryGet is Wait-Free - no locking or spinning. // TryAdd is mostly Wait-Free (may try allocating a new table), but is more complex than TryGet. // // The assumption that same source and target keep the same relationship could be // broken if the types involved are unloaded and their handles are reused. (ABA problem). // To counter that possibility we simply flush the whole cache on assembly unloads. // // Whenever we need to replace or resize the table, we simply allocate a new one and atomically // update the static handle. The old table may be still in use, but will eventually be collected by GC. // class CastCache { #if !defined(DACCESS_COMPILE) static const int VERSION_NUM_SIZE = 29; static const int VERSION_NUM_MASK = (1 << VERSION_NUM_SIZE) - 1; struct CastCacheEntry { // version has the following structure: // [ distance:3bit | versionNum:29bit ] // // distance is how many iterations the entry is from it ideal position. // we use that for preemption. // // versionNum is a monotonicaly increasing numerical tag. // Writer "claims" entry by atomically incrementing the tag. Thus odd number indicates an entry in progress. // Upon completion of adding an entry the tag is incremented again making it even. Even number indicates a complete entry. // // Readers will read the version twice before and after retrieving the entry. // To have a usable entry both reads must yield the same even version. // DWORD version; TADDR source; // pointers have unused lower bits due to alignment, we use one for the result TADDR targetAndResult; FORCEINLINE TADDR Source() { return source; } FORCEINLINE TADDR Target() { return targetAndResult & ~(TADDR)1; } FORCEINLINE BOOL Result() { return targetAndResult & 1; }; FORCEINLINE void SetEntry(TADDR source, TADDR target, BOOL result) { this->source = source; this->targetAndResult = target | (result & 1); } }; public: FORCEINLINE static void TryAddToCache(TypeHandle source, TypeHandle target, BOOL result) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; // fully loaded types cannot be "undone" and thus castability can be cached. // do not cache if any of the types is not fully loaded. if (!source.IsFullyLoaded() || !target.IsFullyLoaded()) return; // we should not be caching T --> Nullable<T>. result is contextual. // unsubsttituted generic T is ok though. there is an agreement on that. _ASSERTE(source.IsTypeDesc() || !Nullable::IsNullableForType(target, source.AsMethodTable())); TryAddToCache(source.AsTAddr(), target.AsTAddr(), result); } FORCEINLINE static void TryAddToCache(MethodTable* pSourceMT, TypeHandle target, BOOL result) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; // fully loaded types cannot be "undone" and thus castability can be cached. // do not cache if any of the types is not fully loaded. if (!pSourceMT->IsFullyLoaded() || !target.IsFullyLoaded()) return; // we should not be caching T --> Nullable<T>. result is contextual. _ASSERTE(!Nullable::IsNullableForType(target, pSourceMT)); TryAddToCache((TADDR)pSourceMT, target.AsTAddr(), result); } FORCEINLINE static TypeHandle::CastResult TryGetFromCache(TypeHandle source, TypeHandle target) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; return TryGetFromCache(source.AsTAddr(), target.AsTAddr()); } FORCEINLINE static TypeHandle::CastResult TryGetFromCache(MethodTable* pSourceMT, TypeHandle target) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; return TryGetFromCache((TADDR)pSourceMT, target.AsTAddr()); } static void FlushCurrentCache(); static void Initialize(); private: // The cache size is driven by demand and generally is fairly small. (casts are repetitive) // Even conversion-churning tests such as Linq.Expressions will not need > 4096 // When we reach the limit, the new entries start replacing the old ones somewhat randomly. // Considering that typically the cache size is small and that hit rates are high with good locality, // just keeping the cache around seems a simple and viable strategy. // // Additional behaviors that could be considered, if there are scenarios that could be improved: // - flush the cache based on some heuristics // - shrink the cache based on some heuristics // #if DEBUG static const DWORD INITIAL_CACHE_SIZE = 8; // MUST BE A POWER OF TWO static const DWORD MAXIMUM_CACHE_SIZE = 512; // make this lower than release to make it easier to reach this in tests. #else static const DWORD INITIAL_CACHE_SIZE = 128; // MUST BE A POWER OF TWO static const DWORD MAXIMUM_CACHE_SIZE = 4096; // 4096 * sizeof(CastCacheEntry) is 98304 bytes on 64bit. We will rarely need this much though. #endif // Lower bucket size will cause the table to resize earlier // Higher bucket size will increase upper bound cost of Get // // In a cold scenario and 64byte cache line: // 1 cache miss for 1 probe, // 2 sequential misses for 3 probes, // then a miss can be assumed for every additional probe. // We pick 8 as the probe limit (hoping for 4 probes on average), but the number can be refined further. static const DWORD BUCKET_SIZE = 8; // current cache table static BASEARRAYREF* s_pTableRef; // sentinel table that never contains elements and used for flushing the old table when we cannot allocate a new one. static OBJECTHANDLE s_sentinelTable; static DWORD s_lastFlushSize; FORCEINLINE static TypeHandle::CastResult TryGetFromCache(TADDR source, TADDR target) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; if (source == target) { return TypeHandle::CanCast; } return TryGet(source, target); } FORCEINLINE static void TryAddToCache(TADDR source, TADDR target, BOOL result) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; if (source == target) return; TrySet(source, target, result); } FORCEINLINE static bool TryGrow(DWORD* tableData) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; DWORD newSize = CacheElementCount(tableData) * 2; if (newSize <= MAXIMUM_CACHE_SIZE) { return MaybeReplaceCacheWithLarger(newSize); } return false; } FORCEINLINE static DWORD KeyToBucket(DWORD* tableData, TADDR source, TADDR target) { // upper bits of addresses do not vary much, so to reduce loss due to cancelling out, // we do `rotl(source, <half-size>) ^ target` for mixing inputs. // then we use fibonacci hashing to reduce the value to desired size. int hashShift = HashShift(tableData); #if HOST_64BIT UINT64 hash = (((UINT64)source << 32) | ((UINT64)source >> 32)) ^ (UINT64)target; return (DWORD)((hash * 11400714819323198485llu) >> hashShift); #else UINT32 hash = (((UINT32)source << 16) | ((UINT32)source >> 16)) ^ (UINT32)target; return (DWORD)((hash * 2654435769ul) >> hashShift); #endif } FORCEINLINE static DWORD* TableData(BASEARRAYREF table) { LIMITED_METHOD_CONTRACT; // element 0 is used for embedded aux data return (DWORD*)((BYTE*)OBJECTREFToObject(table) + ARRAYBASE_SIZE); } FORCEINLINE static CastCacheEntry* Elements(DWORD* tableData) { LIMITED_METHOD_CONTRACT; // element 0 is used for embedded aux data, skip it return (CastCacheEntry*)tableData + 1; } FORCEINLINE static DWORD& HashShift(DWORD* tableData) { LIMITED_METHOD_CONTRACT; return *tableData; } // TableMask is "size - 1" // we need that more often that we need size FORCEINLINE static DWORD& TableMask(DWORD* tableData) { LIMITED_METHOD_CONTRACT; return *(tableData + 1); } FORCEINLINE static DWORD& VictimCounter(DWORD* tableData) { LIMITED_METHOD_CONTRACT; return *(tableData + 2); } FORCEINLINE static DWORD CacheElementCount(DWORD* tableData) { LIMITED_METHOD_CONTRACT; return TableMask(tableData) + 1; } static BASEARRAYREF CreateCastCache(DWORD size); static BOOL MaybeReplaceCacheWithLarger(DWORD size); static TypeHandle::CastResult TryGet(TADDR source, TADDR target); static void TrySet(TADDR source, TADDR target, BOOL result); #else // !DACCESS_COMPILE public: FORCEINLINE static void TryAddToCache(TypeHandle source, TypeHandle target, BOOL result) { } FORCEINLINE static void TryAddToCache(MethodTable* pSourceMT, TypeHandle target, BOOL result) { } FORCEINLINE static TypeHandle::CastResult TryGetFromCache(TypeHandle source, TypeHandle target) { return TypeHandle::MaybeCast; } static void Initialize() { } #endif // !DACCESS_COMPILE }; #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // File: castcache.h // #ifndef _CAST_CACHE_H #define _CAST_CACHE_H #include "util.hpp" // // A very lightweight cache that maps {source, target} -> result, where result is // a boolean value indicating that the type of the source can cast to the target type or // definitely cannot. // // In the terminology of ECMA335 the relationship is called "compatible-with". // This is the relation used by castclass and isinst (III.4.3). // // We generically allow either MethodTable* or TypeHandle as source/target. Either value // uniquely maps to a single type with no possibility of confusion. Besides for most types // TypeHandle a MethodTable* are the same value anyways. // // One thing to consider is that cast analysis is relatively fast, which demands that the cache is fast too. // On the other hand, we do not need to be 100% accurate about a presence of an entry in a cache, // since everything can be re-computed relatively quickly. // We still hope to have a good hit rate, but can tolerate items pushed/flushed from the cache. // // The overal design of the cache is an open-addressing hash table with quadratic probing // strategy and a limited bucket size. // In a case of inserting we - // 1) use an empty entry within the bucket path or preempt an entry with a longer distance from it origin. // 2) pick a random victim entry within the bucket and replace it with a new entry. // That is basically our expiration policy. We want to keep things simple. // // The cache permits fully concurrent writes and stores. We use versioned entries to detect incomplete states and // tearing, which happens temporarily during updating. Entries in an inconsistent state are ignored by readers and writers. // As a result TryGet is Wait-Free - no locking or spinning. // TryAdd is mostly Wait-Free (may try allocating a new table), but is more complex than TryGet. // // The assumption that same source and target keep the same relationship could be // broken if the types involved are unloaded and their handles are reused. (ABA problem). // To counter that possibility we simply flush the whole cache on assembly unloads. // // Whenever we need to replace or resize the table, we simply allocate a new one and atomically // update the static handle. The old table may be still in use, but will eventually be collected by GC. // class CastCache { #if !defined(DACCESS_COMPILE) static const int VERSION_NUM_SIZE = 29; static const int VERSION_NUM_MASK = (1 << VERSION_NUM_SIZE) - 1; struct CastCacheEntry { // version has the following structure: // [ distance:3bit | versionNum:29bit ] // // distance is how many iterations the entry is from it ideal position. // we use that for preemption. // // versionNum is a monotonicaly increasing numerical tag. // Writer "claims" entry by atomically incrementing the tag. Thus odd number indicates an entry in progress. // Upon completion of adding an entry the tag is incremented again making it even. Even number indicates a complete entry. // // Readers will read the version twice before and after retrieving the entry. // To have a usable entry both reads must yield the same even version. // DWORD version; TADDR source; // pointers have unused lower bits due to alignment, we use one for the result TADDR targetAndResult; FORCEINLINE TADDR Source() { return source; } FORCEINLINE TADDR Target() { return targetAndResult & ~(TADDR)1; } FORCEINLINE BOOL Result() { return targetAndResult & 1; }; FORCEINLINE void SetEntry(TADDR source, TADDR target, BOOL result) { this->source = source; this->targetAndResult = target | (result & 1); } }; public: FORCEINLINE static void TryAddToCache(TypeHandle source, TypeHandle target, BOOL result) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; // fully loaded types cannot be "undone" and thus castability can be cached. // do not cache if any of the types is not fully loaded. if (!source.IsFullyLoaded() || !target.IsFullyLoaded()) return; // we should not be caching T --> Nullable<T>. result is contextual. // unsubsttituted generic T is ok though. there is an agreement on that. _ASSERTE(source.IsTypeDesc() || !Nullable::IsNullableForType(target, source.AsMethodTable())); TryAddToCache(source.AsTAddr(), target.AsTAddr(), result); } FORCEINLINE static void TryAddToCache(MethodTable* pSourceMT, TypeHandle target, BOOL result) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; // fully loaded types cannot be "undone" and thus castability can be cached. // do not cache if any of the types is not fully loaded. if (!pSourceMT->IsFullyLoaded() || !target.IsFullyLoaded()) return; // we should not be caching T --> Nullable<T>. result is contextual. _ASSERTE(!Nullable::IsNullableForType(target, pSourceMT)); TryAddToCache((TADDR)pSourceMT, target.AsTAddr(), result); } FORCEINLINE static TypeHandle::CastResult TryGetFromCache(TypeHandle source, TypeHandle target) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; return TryGetFromCache(source.AsTAddr(), target.AsTAddr()); } FORCEINLINE static TypeHandle::CastResult TryGetFromCache(MethodTable* pSourceMT, TypeHandle target) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; return TryGetFromCache((TADDR)pSourceMT, target.AsTAddr()); } static void FlushCurrentCache(); static void Initialize(); private: // The cache size is driven by demand and generally is fairly small. (casts are repetitive) // Even conversion-churning tests such as Linq.Expressions will not need > 4096 // When we reach the limit, the new entries start replacing the old ones somewhat randomly. // Considering that typically the cache size is small and that hit rates are high with good locality, // just keeping the cache around seems a simple and viable strategy. // // Additional behaviors that could be considered, if there are scenarios that could be improved: // - flush the cache based on some heuristics // - shrink the cache based on some heuristics // #if DEBUG static const DWORD INITIAL_CACHE_SIZE = 8; // MUST BE A POWER OF TWO static const DWORD MAXIMUM_CACHE_SIZE = 512; // make this lower than release to make it easier to reach this in tests. #else static const DWORD INITIAL_CACHE_SIZE = 128; // MUST BE A POWER OF TWO static const DWORD MAXIMUM_CACHE_SIZE = 4096; // 4096 * sizeof(CastCacheEntry) is 98304 bytes on 64bit. We will rarely need this much though. #endif // Lower bucket size will cause the table to resize earlier // Higher bucket size will increase upper bound cost of Get // // In a cold scenario and 64byte cache line: // 1 cache miss for 1 probe, // 2 sequential misses for 3 probes, // then a miss can be assumed for every additional probe. // We pick 8 as the probe limit (hoping for 4 probes on average), but the number can be refined further. static const DWORD BUCKET_SIZE = 8; // current cache table static BASEARRAYREF* s_pTableRef; // sentinel table that never contains elements and used for flushing the old table when we cannot allocate a new one. static OBJECTHANDLE s_sentinelTable; static DWORD s_lastFlushSize; FORCEINLINE static TypeHandle::CastResult TryGetFromCache(TADDR source, TADDR target) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; if (source == target) { return TypeHandle::CanCast; } return TryGet(source, target); } FORCEINLINE static void TryAddToCache(TADDR source, TADDR target, BOOL result) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; if (source == target) return; TrySet(source, target, result); } FORCEINLINE static bool TryGrow(DWORD* tableData) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; DWORD newSize = CacheElementCount(tableData) * 2; if (newSize <= MAXIMUM_CACHE_SIZE) { return MaybeReplaceCacheWithLarger(newSize); } return false; } FORCEINLINE static DWORD KeyToBucket(DWORD* tableData, TADDR source, TADDR target) { // upper bits of addresses do not vary much, so to reduce loss due to cancelling out, // we do `rotl(source, <half-size>) ^ target` for mixing inputs. // then we use fibonacci hashing to reduce the value to desired size. int hashShift = HashShift(tableData); #if HOST_64BIT UINT64 hash = (((UINT64)source << 32) | ((UINT64)source >> 32)) ^ (UINT64)target; return (DWORD)((hash * 11400714819323198485llu) >> hashShift); #else UINT32 hash = (((UINT32)source << 16) | ((UINT32)source >> 16)) ^ (UINT32)target; return (DWORD)((hash * 2654435769ul) >> hashShift); #endif } FORCEINLINE static DWORD* TableData(BASEARRAYREF table) { LIMITED_METHOD_CONTRACT; // element 0 is used for embedded aux data return (DWORD*)((BYTE*)OBJECTREFToObject(table) + ARRAYBASE_SIZE); } FORCEINLINE static CastCacheEntry* Elements(DWORD* tableData) { LIMITED_METHOD_CONTRACT; // element 0 is used for embedded aux data, skip it return (CastCacheEntry*)tableData + 1; } FORCEINLINE static DWORD& HashShift(DWORD* tableData) { LIMITED_METHOD_CONTRACT; return *tableData; } // TableMask is "size - 1" // we need that more often that we need size FORCEINLINE static DWORD& TableMask(DWORD* tableData) { LIMITED_METHOD_CONTRACT; return *(tableData + 1); } FORCEINLINE static DWORD& VictimCounter(DWORD* tableData) { LIMITED_METHOD_CONTRACT; return *(tableData + 2); } FORCEINLINE static DWORD CacheElementCount(DWORD* tableData) { LIMITED_METHOD_CONTRACT; return TableMask(tableData) + 1; } static BASEARRAYREF CreateCastCache(DWORD size); static BOOL MaybeReplaceCacheWithLarger(DWORD size); static TypeHandle::CastResult TryGet(TADDR source, TADDR target); static void TrySet(TADDR source, TADDR target, BOOL result); #else // !DACCESS_COMPILE public: FORCEINLINE static void TryAddToCache(TypeHandle source, TypeHandle target, BOOL result) { } FORCEINLINE static void TryAddToCache(MethodTable* pSourceMT, TypeHandle target, BOOL result) { } FORCEINLINE static TypeHandle::CastResult TryGetFromCache(TypeHandle source, TypeHandle target) { return TypeHandle::MaybeCast; } static void Initialize() { } #endif // !DACCESS_COMPILE }; #endif
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/inc/ceegen.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // =========================================================================== // File: CEEGEN.H // // =========================================================================== #ifndef _CEEGEN_H_ #define _CEEGEN_H_ #include "cor.h" #include "iceefilegen.h" #include "ceegentokenmapper.h" class CeeSection; class CeeSectionString; class CCeeGen; class PESectionMan; class PESection; typedef DWORD StringRef; #if 0 This is a description of the current implementation of these types for generating CLR modules. ICeeGenInternal - interface to generate in-memory CLR module. CCeeGen - implementation of ICeeGen. Currently it uses both CeeSections as well as PESections (inside PESectionMan), and maintains a 1:1 relation between them. This is ugly. CeeFileGenWriter - Provides functionality to write in-memory module to PE format file. Uses PEWriter (m_pSectionMan) for file-writing functionality PEWriter - It can generate a PE format file. It also knows to apply pointer relocs when it lays out the PESections. ICeeFileGen - Interface used by compilers, ngen, etc, to generate a CLR file. Has a bunch of methods to emit signatures, tokens, methods, etc which are not implemented. These are left over from before +----------------------------+ | ICeeGenInternal | | | | COM-style version of | | ICeeFileGen. HCEEFILE is | | replaced with "this" | +-------------------------+ | | | CeeSectionImpl | +----------------------------+ +-------------------------+ | | | | | | v | v +---------------------------+ | +------------+ | CCeeGen | | | | +---------------------------+ | | CeeSection | contains | | | | |<-------------| CeeSection* m_sections | | +------------+ | | | /| PESectionMan m_pSectionMan| | / | | | +-----------------+ / +---------------------------+ v | PESectionMan |<----+ | +-----------+ | | contains | | PESection | +-----------------+ | | | contains | PESection * | v | |<----------| sectStart, | +------------------------------+ +-----------+ | sectCur, | | CeeFileGenWriter | | sectEnd | +------------------------------+ +-----------------+ | Does meta-data specific | | | stuff and then dispatches to | | | m_pSectionMan.PEWriter::***()| | | | v +------------------------------+ +------------------------+ ^ | PEWriter | |wraps +------------------------+ | | Low -level file writer | +----------------------------+ | Knows how to do | | ICeeFileGen | | pointer relocs | | | | | | C-style inteface. Deals | +------------------------+ | with HCEEFILE, HCEESECTION | | etc. It is mostly just a | | thin wrapper for a | | CeeFileGenWriter | +----------------------------+ #endif // 0 // ***** CeeSection classes class CeeSectionImpl { public: virtual unsigned dataLen() = 0; virtual char * getBlock( unsigned len, unsigned align = 1) = 0; virtual HRESULT addSectReloc( unsigned offset, CeeSection & relativeTo, CeeSectionRelocType reloc = srRelocAbsolute, CeeSectionRelocExtra * extra = NULL) = 0; virtual HRESULT addBaseReloc( unsigned offset, CeeSectionRelocType reloc = srRelocHighLow, CeeSectionRelocExtra * extra = NULL) = 0; virtual HRESULT directoryEntry(unsigned num) = 0; virtual unsigned char * name() = 0; virtual char * computePointer(unsigned offset) const = 0; virtual BOOL containsPointer(_In_ char * ptr) const = 0; virtual unsigned computeOffset(_In_ char * ptr) const = 0; virtual unsigned getBaseRVA() = 0; virtual void SetInitialGrowth(unsigned growth) = 0; }; class CeeSection { // m_ceeFile allows inter-section communication CCeeGen &m_ceeFile; // abstract away implementation to allow inheritance from CeeSection CeeSectionImpl &m_impl; public: enum RelocFlags { RELOC_NONE = 0, // address should be fixed up to be a RVA not a normal address RELOC_RVA = 1 }; CeeSection(CCeeGen &ceeFile, CeeSectionImpl &impl) : m_ceeFile(ceeFile), m_impl(impl) { LIMITED_METHOD_CONTRACT; } virtual ~CeeSection() {LIMITED_METHOD_CONTRACT; } // bytes in this section at present unsigned dataLen(); // section base, after linking unsigned getBaseRVA(); // get a block to write on (use instead of write to avoid copy) char* getBlock(unsigned len, unsigned align=1); // Indicates that the DWORD at 'offset' in the current section should // have the base of section 'relativeTo added to it HRESULT addSectReloc(unsigned offset, CeeSection& relativeTo, CeeSectionRelocType = srRelocAbsolute, CeeSectionRelocExtra *extra = 0); // Add a base reloc for the given offset in the current section virtual HRESULT addBaseReloc(unsigned offset, CeeSectionRelocType reloc = srRelocHighLow, CeeSectionRelocExtra *extra = 0); // this section will be directory entry 'num' HRESULT directoryEntry(unsigned num); // return section name unsigned char *name(); // simulate the base + offset with a more complex data storage char * computePointer(unsigned offset) const; BOOL containsPointer(_In_ char *ptr) const; unsigned computeOffset(_In_ char *ptr) const; CeeSectionImpl &getImpl(); CCeeGen &ceeFile(); void SetInitialGrowth(unsigned growth); }; // ***** CCeeGen class // Only handles in memory stuff // Base class for CeeFileGenWriter (which actually generates PEFiles) class CCeeGen : public ICeeGenInternal { LONG m_cRefs; protected: short m_textIdx; // m_sections[] index for the .text section short m_metaIdx; // m_sections[] index for metadata (.text, or .cormeta for obj files) short m_corHdrIdx; // m_sections[] index for the COM+ header (.text0) short m_stringIdx; // m_sections[] index for strings (.text, or .rdata for EnC) short m_ilIdx; // m_sections[] index for IL (.text) CeeGenTokenMapper *m_pTokenMap; BOOLEAN m_fTokenMapSupported; // temporary to support both models IMapToken *m_pRemapHandler; CeeSection **m_sections; short m_numSections; short m_allocSections; PESectionMan * m_peSectionMan; IMAGE_COR20_HEADER *m_corHeader; DWORD m_corHeaderOffset; HRESULT allocateCorHeader(); HRESULT addSection(CeeSection *section, short *sectionIdx); // Init process: Call static CreateNewInstance() , not operator new protected: HRESULT Init(); CCeeGen(); public: virtual ~CCeeGen() {} static HRESULT CreateNewInstance(CCeeGen* & pCeeFileGen); // call this to instantiate virtual HRESULT Cleanup(); // ICeeGenInternal interfaces ULONG STDMETHODCALLTYPE AddRef(); ULONG STDMETHODCALLTYPE Release(); STDMETHODIMP QueryInterface( REFIID riid, void **ppInterface); STDMETHODIMP EmitString ( _In_ LPWSTR lpString, // [IN] String to emit ULONG *RVA); STDMETHODIMP GetString ( ULONG RVA, __inout LPWSTR *lpString); STDMETHODIMP AllocateMethodBuffer ( ULONG cchBuffer, // [IN] Length of string to emit UCHAR **lpBuffer, // [OUT] Returned buffer ULONG *RVA); STDMETHODIMP GetMethodBuffer ( ULONG RVA, UCHAR **lpBuffer); STDMETHODIMP GetIMapTokenIface ( IUnknown **pIMapToken); STDMETHODIMP GenerateCeeFile (); STDMETHODIMP GetIlSection ( HCEESECTION *section); STDMETHODIMP GetStringSection ( HCEESECTION *section); STDMETHODIMP AddSectionReloc ( HCEESECTION section, ULONG offset, HCEESECTION relativeTo, CeeSectionRelocType relocType); STDMETHODIMP GetSectionCreate ( const char *name, DWORD flags, HCEESECTION *section); STDMETHODIMP GetSectionDataLen ( HCEESECTION section, ULONG *dataLen); STDMETHODIMP GetSectionBlock ( HCEESECTION section, ULONG len, ULONG align=1, void **ppBytes=0); STDMETHODIMP ComputePointer ( HCEESECTION section, ULONG RVA, // [IN] RVA for method to return UCHAR **lpBuffer); // [OUT] Returned buffer STDMETHODIMP AddNotificationHandler(IUnknown *pHandler); // Write the metadata in "emitter" to the default metadata section is "section" is 0 // If 'section != 0, it will put the data in 'buffer'. This // buffer is assumed to be in 'section' at 'offset' and of size 'buffLen' // (should use GetSaveSize to insure that buffer is big enough virtual HRESULT emitMetaData(IMetaDataEmit *emitter, CeeSection* section=0, DWORD offset=0, BYTE* buffer=0, unsigned buffLen=0); virtual HRESULT getMethodRVA(ULONG codeOffset, ULONG *codeRVA); STDMETHODIMP SetInitialGrowth(DWORD growth); CeeSection &getTextSection(); CeeSection &getMetaSection(); CeeSection &getCorHeaderSection(); CeeSectionString &getStringSection(); CeeSection &getIlSection(); virtual HRESULT getSectionCreate (const char *name, DWORD flags, CeeSection **section=NULL, short *sectionIdx = NULL); PESectionMan* getPESectionMan() { LIMITED_METHOD_CONTRACT; return m_peSectionMan; } virtual HRESULT getMapTokenIface(IUnknown **pIMapToken, IMetaDataEmit *emitter=0); CeeGenTokenMapper *getTokenMapper() { LIMITED_METHOD_CONTRACT; return m_pTokenMap; } virtual HRESULT addNotificationHandler(IUnknown *pHandler); //Clone is actually a misnomer here. This method will copy all of the //instance variables and then do a deep copy (as necessary) of the sections. //Section data will be appended onto any information already in the section. //This is done to support the DynamicIL -> PersistedIL transform. virtual HRESULT cloneInstance(CCeeGen *destination); }; // ***** CeeSection inline methods inline unsigned CeeSection::dataLen() { WRAPPER_NO_CONTRACT; return m_impl.dataLen(); } inline unsigned CeeSection::getBaseRVA() { WRAPPER_NO_CONTRACT; return m_impl.getBaseRVA(); } inline char *CeeSection::getBlock(unsigned len, unsigned align) { WRAPPER_NO_CONTRACT; return m_impl.getBlock(len, align); } inline HRESULT CeeSection::addSectReloc( unsigned offset, CeeSection& relativeTo, CeeSectionRelocType reloc, CeeSectionRelocExtra *extra) { WRAPPER_NO_CONTRACT; return(m_impl.addSectReloc(offset, relativeTo, reloc, extra)); } inline HRESULT CeeSection::addBaseReloc(unsigned offset, CeeSectionRelocType reloc, CeeSectionRelocExtra *extra) { WRAPPER_NO_CONTRACT; return(m_impl.addBaseReloc(offset, reloc, extra)); } inline HRESULT CeeSection::directoryEntry(unsigned num) { WRAPPER_NO_CONTRACT; TESTANDRETURN(num < IMAGE_NUMBEROF_DIRECTORY_ENTRIES, E_INVALIDARG); m_impl.directoryEntry(num); return S_OK; } inline CCeeGen &CeeSection::ceeFile() { LIMITED_METHOD_CONTRACT; return m_ceeFile; } inline CeeSectionImpl &CeeSection::getImpl() { LIMITED_METHOD_CONTRACT; return m_impl; } inline unsigned char *CeeSection::name() { WRAPPER_NO_CONTRACT; return m_impl.name(); } inline char * CeeSection::computePointer(unsigned offset) const { WRAPPER_NO_CONTRACT; return m_impl.computePointer(offset); } inline BOOL CeeSection::containsPointer(_In_ char *ptr) const { WRAPPER_NO_CONTRACT; return m_impl.containsPointer(ptr); } inline unsigned CeeSection::computeOffset(_In_ char *ptr) const { WRAPPER_NO_CONTRACT; return m_impl.computeOffset(ptr); } inline void CeeSection::SetInitialGrowth(unsigned growth) { WRAPPER_NO_CONTRACT; m_impl.SetInitialGrowth(growth); } // ***** CCeeGen inline methods inline CeeSection &CCeeGen::getTextSection() { LIMITED_METHOD_CONTRACT; return *m_sections[m_textIdx]; } inline CeeSection &CCeeGen::getMetaSection() { LIMITED_METHOD_CONTRACT; return *m_sections[m_metaIdx]; } inline CeeSection &CCeeGen::getCorHeaderSection() { LIMITED_METHOD_CONTRACT; _ASSERTE(m_corHdrIdx >= 0); return *m_sections[m_corHdrIdx]; } inline CeeSectionString &CCeeGen::getStringSection() { LIMITED_METHOD_CONTRACT; return *(CeeSectionString*)m_sections[m_stringIdx]; } inline CeeSection &CCeeGen::getIlSection() { LIMITED_METHOD_CONTRACT; return *m_sections[m_ilIdx]; } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // =========================================================================== // File: CEEGEN.H // // =========================================================================== #ifndef _CEEGEN_H_ #define _CEEGEN_H_ #include "cor.h" #include "iceefilegen.h" #include "ceegentokenmapper.h" class CeeSection; class CeeSectionString; class CCeeGen; class PESectionMan; class PESection; typedef DWORD StringRef; #if 0 This is a description of the current implementation of these types for generating CLR modules. ICeeGenInternal - interface to generate in-memory CLR module. CCeeGen - implementation of ICeeGen. Currently it uses both CeeSections as well as PESections (inside PESectionMan), and maintains a 1:1 relation between them. This is ugly. CeeFileGenWriter - Provides functionality to write in-memory module to PE format file. Uses PEWriter (m_pSectionMan) for file-writing functionality PEWriter - It can generate a PE format file. It also knows to apply pointer relocs when it lays out the PESections. ICeeFileGen - Interface used by compilers, ngen, etc, to generate a CLR file. Has a bunch of methods to emit signatures, tokens, methods, etc which are not implemented. These are left over from before +----------------------------+ | ICeeGenInternal | | | | COM-style version of | | ICeeFileGen. HCEEFILE is | | replaced with "this" | +-------------------------+ | | | CeeSectionImpl | +----------------------------+ +-------------------------+ | | | | | | v | v +---------------------------+ | +------------+ | CCeeGen | | | | +---------------------------+ | | CeeSection | contains | | | | |<-------------| CeeSection* m_sections | | +------------+ | | | /| PESectionMan m_pSectionMan| | / | | | +-----------------+ / +---------------------------+ v | PESectionMan |<----+ | +-----------+ | | contains | | PESection | +-----------------+ | | | contains | PESection * | v | |<----------| sectStart, | +------------------------------+ +-----------+ | sectCur, | | CeeFileGenWriter | | sectEnd | +------------------------------+ +-----------------+ | Does meta-data specific | | | stuff and then dispatches to | | | m_pSectionMan.PEWriter::***()| | | | v +------------------------------+ +------------------------+ ^ | PEWriter | |wraps +------------------------+ | | Low -level file writer | +----------------------------+ | Knows how to do | | ICeeFileGen | | pointer relocs | | | | | | C-style inteface. Deals | +------------------------+ | with HCEEFILE, HCEESECTION | | etc. It is mostly just a | | thin wrapper for a | | CeeFileGenWriter | +----------------------------+ #endif // 0 // ***** CeeSection classes class CeeSectionImpl { public: virtual unsigned dataLen() = 0; virtual char * getBlock( unsigned len, unsigned align = 1) = 0; virtual HRESULT addSectReloc( unsigned offset, CeeSection & relativeTo, CeeSectionRelocType reloc = srRelocAbsolute, CeeSectionRelocExtra * extra = NULL) = 0; virtual HRESULT addBaseReloc( unsigned offset, CeeSectionRelocType reloc = srRelocHighLow, CeeSectionRelocExtra * extra = NULL) = 0; virtual HRESULT directoryEntry(unsigned num) = 0; virtual unsigned char * name() = 0; virtual char * computePointer(unsigned offset) const = 0; virtual BOOL containsPointer(_In_ char * ptr) const = 0; virtual unsigned computeOffset(_In_ char * ptr) const = 0; virtual unsigned getBaseRVA() = 0; virtual void SetInitialGrowth(unsigned growth) = 0; }; class CeeSection { // m_ceeFile allows inter-section communication CCeeGen &m_ceeFile; // abstract away implementation to allow inheritance from CeeSection CeeSectionImpl &m_impl; public: enum RelocFlags { RELOC_NONE = 0, // address should be fixed up to be a RVA not a normal address RELOC_RVA = 1 }; CeeSection(CCeeGen &ceeFile, CeeSectionImpl &impl) : m_ceeFile(ceeFile), m_impl(impl) { LIMITED_METHOD_CONTRACT; } virtual ~CeeSection() {LIMITED_METHOD_CONTRACT; } // bytes in this section at present unsigned dataLen(); // section base, after linking unsigned getBaseRVA(); // get a block to write on (use instead of write to avoid copy) char* getBlock(unsigned len, unsigned align=1); // Indicates that the DWORD at 'offset' in the current section should // have the base of section 'relativeTo added to it HRESULT addSectReloc(unsigned offset, CeeSection& relativeTo, CeeSectionRelocType = srRelocAbsolute, CeeSectionRelocExtra *extra = 0); // Add a base reloc for the given offset in the current section virtual HRESULT addBaseReloc(unsigned offset, CeeSectionRelocType reloc = srRelocHighLow, CeeSectionRelocExtra *extra = 0); // this section will be directory entry 'num' HRESULT directoryEntry(unsigned num); // return section name unsigned char *name(); // simulate the base + offset with a more complex data storage char * computePointer(unsigned offset) const; BOOL containsPointer(_In_ char *ptr) const; unsigned computeOffset(_In_ char *ptr) const; CeeSectionImpl &getImpl(); CCeeGen &ceeFile(); void SetInitialGrowth(unsigned growth); }; // ***** CCeeGen class // Only handles in memory stuff // Base class for CeeFileGenWriter (which actually generates PEFiles) class CCeeGen : public ICeeGenInternal { LONG m_cRefs; protected: short m_textIdx; // m_sections[] index for the .text section short m_metaIdx; // m_sections[] index for metadata (.text, or .cormeta for obj files) short m_corHdrIdx; // m_sections[] index for the COM+ header (.text0) short m_stringIdx; // m_sections[] index for strings (.text, or .rdata for EnC) short m_ilIdx; // m_sections[] index for IL (.text) CeeGenTokenMapper *m_pTokenMap; BOOLEAN m_fTokenMapSupported; // temporary to support both models IMapToken *m_pRemapHandler; CeeSection **m_sections; short m_numSections; short m_allocSections; PESectionMan * m_peSectionMan; IMAGE_COR20_HEADER *m_corHeader; DWORD m_corHeaderOffset; HRESULT allocateCorHeader(); HRESULT addSection(CeeSection *section, short *sectionIdx); // Init process: Call static CreateNewInstance() , not operator new protected: HRESULT Init(); CCeeGen(); public: virtual ~CCeeGen() {} static HRESULT CreateNewInstance(CCeeGen* & pCeeFileGen); // call this to instantiate virtual HRESULT Cleanup(); // ICeeGenInternal interfaces ULONG STDMETHODCALLTYPE AddRef(); ULONG STDMETHODCALLTYPE Release(); STDMETHODIMP QueryInterface( REFIID riid, void **ppInterface); STDMETHODIMP EmitString ( _In_ LPWSTR lpString, // [IN] String to emit ULONG *RVA); STDMETHODIMP GetString ( ULONG RVA, __inout LPWSTR *lpString); STDMETHODIMP AllocateMethodBuffer ( ULONG cchBuffer, // [IN] Length of string to emit UCHAR **lpBuffer, // [OUT] Returned buffer ULONG *RVA); STDMETHODIMP GetMethodBuffer ( ULONG RVA, UCHAR **lpBuffer); STDMETHODIMP GetIMapTokenIface ( IUnknown **pIMapToken); STDMETHODIMP GenerateCeeFile (); STDMETHODIMP GetIlSection ( HCEESECTION *section); STDMETHODIMP GetStringSection ( HCEESECTION *section); STDMETHODIMP AddSectionReloc ( HCEESECTION section, ULONG offset, HCEESECTION relativeTo, CeeSectionRelocType relocType); STDMETHODIMP GetSectionCreate ( const char *name, DWORD flags, HCEESECTION *section); STDMETHODIMP GetSectionDataLen ( HCEESECTION section, ULONG *dataLen); STDMETHODIMP GetSectionBlock ( HCEESECTION section, ULONG len, ULONG align=1, void **ppBytes=0); STDMETHODIMP ComputePointer ( HCEESECTION section, ULONG RVA, // [IN] RVA for method to return UCHAR **lpBuffer); // [OUT] Returned buffer STDMETHODIMP AddNotificationHandler(IUnknown *pHandler); // Write the metadata in "emitter" to the default metadata section is "section" is 0 // If 'section != 0, it will put the data in 'buffer'. This // buffer is assumed to be in 'section' at 'offset' and of size 'buffLen' // (should use GetSaveSize to insure that buffer is big enough virtual HRESULT emitMetaData(IMetaDataEmit *emitter, CeeSection* section=0, DWORD offset=0, BYTE* buffer=0, unsigned buffLen=0); virtual HRESULT getMethodRVA(ULONG codeOffset, ULONG *codeRVA); STDMETHODIMP SetInitialGrowth(DWORD growth); CeeSection &getTextSection(); CeeSection &getMetaSection(); CeeSection &getCorHeaderSection(); CeeSectionString &getStringSection(); CeeSection &getIlSection(); virtual HRESULT getSectionCreate (const char *name, DWORD flags, CeeSection **section=NULL, short *sectionIdx = NULL); PESectionMan* getPESectionMan() { LIMITED_METHOD_CONTRACT; return m_peSectionMan; } virtual HRESULT getMapTokenIface(IUnknown **pIMapToken, IMetaDataEmit *emitter=0); CeeGenTokenMapper *getTokenMapper() { LIMITED_METHOD_CONTRACT; return m_pTokenMap; } virtual HRESULT addNotificationHandler(IUnknown *pHandler); //Clone is actually a misnomer here. This method will copy all of the //instance variables and then do a deep copy (as necessary) of the sections. //Section data will be appended onto any information already in the section. //This is done to support the DynamicIL -> PersistedIL transform. virtual HRESULT cloneInstance(CCeeGen *destination); }; // ***** CeeSection inline methods inline unsigned CeeSection::dataLen() { WRAPPER_NO_CONTRACT; return m_impl.dataLen(); } inline unsigned CeeSection::getBaseRVA() { WRAPPER_NO_CONTRACT; return m_impl.getBaseRVA(); } inline char *CeeSection::getBlock(unsigned len, unsigned align) { WRAPPER_NO_CONTRACT; return m_impl.getBlock(len, align); } inline HRESULT CeeSection::addSectReloc( unsigned offset, CeeSection& relativeTo, CeeSectionRelocType reloc, CeeSectionRelocExtra *extra) { WRAPPER_NO_CONTRACT; return(m_impl.addSectReloc(offset, relativeTo, reloc, extra)); } inline HRESULT CeeSection::addBaseReloc(unsigned offset, CeeSectionRelocType reloc, CeeSectionRelocExtra *extra) { WRAPPER_NO_CONTRACT; return(m_impl.addBaseReloc(offset, reloc, extra)); } inline HRESULT CeeSection::directoryEntry(unsigned num) { WRAPPER_NO_CONTRACT; TESTANDRETURN(num < IMAGE_NUMBEROF_DIRECTORY_ENTRIES, E_INVALIDARG); m_impl.directoryEntry(num); return S_OK; } inline CCeeGen &CeeSection::ceeFile() { LIMITED_METHOD_CONTRACT; return m_ceeFile; } inline CeeSectionImpl &CeeSection::getImpl() { LIMITED_METHOD_CONTRACT; return m_impl; } inline unsigned char *CeeSection::name() { WRAPPER_NO_CONTRACT; return m_impl.name(); } inline char * CeeSection::computePointer(unsigned offset) const { WRAPPER_NO_CONTRACT; return m_impl.computePointer(offset); } inline BOOL CeeSection::containsPointer(_In_ char *ptr) const { WRAPPER_NO_CONTRACT; return m_impl.containsPointer(ptr); } inline unsigned CeeSection::computeOffset(_In_ char *ptr) const { WRAPPER_NO_CONTRACT; return m_impl.computeOffset(ptr); } inline void CeeSection::SetInitialGrowth(unsigned growth) { WRAPPER_NO_CONTRACT; m_impl.SetInitialGrowth(growth); } // ***** CCeeGen inline methods inline CeeSection &CCeeGen::getTextSection() { LIMITED_METHOD_CONTRACT; return *m_sections[m_textIdx]; } inline CeeSection &CCeeGen::getMetaSection() { LIMITED_METHOD_CONTRACT; return *m_sections[m_metaIdx]; } inline CeeSection &CCeeGen::getCorHeaderSection() { LIMITED_METHOD_CONTRACT; _ASSERTE(m_corHdrIdx >= 0); return *m_sections[m_corHdrIdx]; } inline CeeSectionString &CCeeGen::getStringSection() { LIMITED_METHOD_CONTRACT; return *(CeeSectionString*)m_sections[m_stringIdx]; } inline CeeSection &CCeeGen::getIlSection() { LIMITED_METHOD_CONTRACT; return *m_sections[m_ilIdx]; } #endif
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/gc/dac_gcheap_fields.h
DEFINE_FIELD (alloc_allocated, uint8_t*) DEFINE_DPTR_FIELD (ephemeral_heap_segment, dac_heap_segment) DEFINE_DPTR_FIELD (finalize_queue, dac_finalize_queue) DEFINE_FIELD (oom_info, oom_history) DEFINE_ARRAY_FIELD (interesting_data_per_heap, size_t, NUM_GC_DATA_POINTS) DEFINE_ARRAY_FIELD (compact_reasons_per_heap, size_t, MAX_COMPACT_REASONS_COUNT) DEFINE_ARRAY_FIELD (expand_mechanisms_per_heap, size_t, MAX_EXPAND_MECHANISMS_COUNT) DEFINE_ARRAY_FIELD (interesting_mechanism_bits_per_heap,size_t, MAX_GC_MECHANISM_BITS_COUNT) DEFINE_FIELD (internal_root_array, uint8_t*) DEFINE_FIELD (internal_root_array_index, size_t) DEFINE_FIELD (heap_analyze_success, BOOL) DEFINE_FIELD (card_table, uint32_t*) #if defined(ALL_FIELDS) || defined(BACKGROUND_GC) DEFINE_FIELD (mark_array, uint32_t*) DEFINE_FIELD (next_sweep_obj, uint8_t*) DEFINE_FIELD (background_saved_lowest_address, uint8_t*) DEFINE_FIELD (background_saved_highest_address, uint8_t*) #if defined(ALL_FIELDS) || !defined(USE_REGIONS) DEFINE_DPTR_FIELD (saved_sweep_ephemeral_seg, dac_heap_segment) DEFINE_FIELD (saved_sweep_ephemeral_start, uint8_t*) #else DEFINE_MISSING_FIELD(saved_sweep_ephemeral_seg) DEFINE_MISSING_FIELD(saved_sweep_ephemeral_start) #endif #else DEFINE_MISSING_FIELD(mark_array) DEFINE_MISSING_FIELD(next_sweep_obj) DEFINE_MISSING_FIELD(background_saved_lowest_address) DEFINE_MISSING_FIELD(background_saved_highest_address) DEFINE_MISSING_FIELD(saved_sweep_ephemeral_seg) DEFINE_MISSING_FIELD(saved_sweep_ephemeral_start) #endif
DEFINE_FIELD (alloc_allocated, uint8_t*) DEFINE_DPTR_FIELD (ephemeral_heap_segment, dac_heap_segment) DEFINE_DPTR_FIELD (finalize_queue, dac_finalize_queue) DEFINE_FIELD (oom_info, oom_history) DEFINE_ARRAY_FIELD (interesting_data_per_heap, size_t, NUM_GC_DATA_POINTS) DEFINE_ARRAY_FIELD (compact_reasons_per_heap, size_t, MAX_COMPACT_REASONS_COUNT) DEFINE_ARRAY_FIELD (expand_mechanisms_per_heap, size_t, MAX_EXPAND_MECHANISMS_COUNT) DEFINE_ARRAY_FIELD (interesting_mechanism_bits_per_heap,size_t, MAX_GC_MECHANISM_BITS_COUNT) DEFINE_FIELD (internal_root_array, uint8_t*) DEFINE_FIELD (internal_root_array_index, size_t) DEFINE_FIELD (heap_analyze_success, BOOL) DEFINE_FIELD (card_table, uint32_t*) #if defined(ALL_FIELDS) || defined(BACKGROUND_GC) DEFINE_FIELD (mark_array, uint32_t*) DEFINE_FIELD (next_sweep_obj, uint8_t*) DEFINE_FIELD (background_saved_lowest_address, uint8_t*) DEFINE_FIELD (background_saved_highest_address, uint8_t*) #if defined(ALL_FIELDS) || !defined(USE_REGIONS) DEFINE_DPTR_FIELD (saved_sweep_ephemeral_seg, dac_heap_segment) DEFINE_FIELD (saved_sweep_ephemeral_start, uint8_t*) #else DEFINE_MISSING_FIELD(saved_sweep_ephemeral_seg) DEFINE_MISSING_FIELD(saved_sweep_ephemeral_start) #endif #else DEFINE_MISSING_FIELD(mark_array) DEFINE_MISSING_FIELD(next_sweep_obj) DEFINE_MISSING_FIELD(background_saved_lowest_address) DEFINE_MISSING_FIELD(background_saved_highest_address) DEFINE_MISSING_FIELD(saved_sweep_ephemeral_seg) DEFINE_MISSING_FIELD(saved_sweep_ephemeral_start) #endif
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/md/inc/portablepdbmdi.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /***************************************************************************** ** ** ** portablepdbmdi.h - contains COM interface definitions for portable PDB ** ** metadata generation. ** ** ** *****************************************************************************/ #ifndef _PORTABLEPDBMDI_H_ #define _PORTABLEPDBMDI_H_ #if _MSC_VER >= 1100 #pragma once #endif #include "cor.h" #include "portablepdbmdds.h" #ifdef __cplusplus extern "C" { #endif //------------------------------------- //--- IMetaDataEmit3 //------------------------------------- // {1a5abcd7-854e-4f07-ace4-3f09e6092939} EXTERN_GUID(IID_IMetaDataEmit3, 0x1a5abcd7, 0x854e, 0x4f07, 0xac, 0xe4, 0x3f, 0x09, 0xe6, 0x09, 0x29, 0x39); //--- #undef INTERFACE #define INTERFACE IMetaDataEmit3 DECLARE_INTERFACE_(IMetaDataEmit3, IMetaDataEmit2) { STDMETHOD(GetReferencedTypeSysTables)( // S_OK or error. ULONG64 *refTables, // [OUT] Bit vector of referenced type system metadata tables. ULONG refTableRows[], // [OUT] Array of number of rows for each referenced type system table. const ULONG maxTableRowsSize, // [IN] Max size of the rows array. ULONG *tableRowsSize) PURE; // [OUT] Actual size of the rows array. STDMETHOD(DefinePdbStream)( // S_OK or error. PORT_PDB_STREAM *pdbStream) PURE; // [IN] Portable pdb stream data. STDMETHOD(DefineDocument)( // S_OK or error. char *docName, // [IN] Document name (string will be tokenized). GUID *hashAlg, // [IN] Hash algorithm GUID. BYTE *hashVal, // [IN] Hash value. ULONG hashValSize, // [IN] Hash value size. GUID *lang, // [IN] Language GUID. mdDocument *docMdToken) PURE; // [OUT] Token of the defined document. STDMETHOD(DefineSequencePoints)( // S_OK or error. ULONG docRid, // [IN] Document RID. BYTE *sequencePtsBlob, // [IN] Sequence point blob. ULONG sequencePtsBlobSize) PURE; // [IN] Sequence point blob size. STDMETHOD(DefineLocalScope)( // S_OK or error. ULONG methodDefRid, // [IN] Method RID. ULONG importScopeRid, // [IN] Import scope RID. ULONG firstLocalVarRid, // [IN] First local variable RID (of the continous run). ULONG firstLocalConstRid, // [IN] First local constant RID (of the continous run). ULONG startOffset, // [IN] Start offset of the scope. ULONG length) PURE; // [IN] Scope length. STDMETHOD(DefineLocalVariable)( // S_OK or error. USHORT attribute, // [IN] Variable attribute. USHORT index, // [IN] Variable index (slot). char *name, // [IN] Variable name. mdLocalVariable *locVarToken) PURE; // [OUT] Token of the defined variable. }; //------------------------------------- //--- IMetaDataDispenserEx2 //------------------------------------- // {23aaef0d-49bf-43f0-9744-1c3e9c56322a} EXTERN_GUID(IID_IMetaDataDispenserEx2, 0x23aaef0d, 0x49bf, 0x43f0, 0x97, 0x44, 0x1c, 0x3e, 0x9c, 0x56, 0x32, 0x2a); #undef INTERFACE #define INTERFACE IMetaDataDispenserEx2 DECLARE_INTERFACE_(IMetaDataDispenserEx2, IMetaDataDispenserEx) { STDMETHOD(DefinePortablePdbScope)( // Return code. REFCLSID rclsid, // [IN] What version to create. DWORD dwCreateFlags, // [IN] Flags on the create. REFIID riid, // [IN] The interface desired. IUnknown * *ppIUnk) PURE; // [OUT] Return interface on success. }; #ifdef __cplusplus } #endif #endif // _PORTABLEPDBMDI_H_
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /***************************************************************************** ** ** ** portablepdbmdi.h - contains COM interface definitions for portable PDB ** ** metadata generation. ** ** ** *****************************************************************************/ #ifndef _PORTABLEPDBMDI_H_ #define _PORTABLEPDBMDI_H_ #if _MSC_VER >= 1100 #pragma once #endif #include "cor.h" #include "portablepdbmdds.h" #ifdef __cplusplus extern "C" { #endif //------------------------------------- //--- IMetaDataEmit3 //------------------------------------- // {1a5abcd7-854e-4f07-ace4-3f09e6092939} EXTERN_GUID(IID_IMetaDataEmit3, 0x1a5abcd7, 0x854e, 0x4f07, 0xac, 0xe4, 0x3f, 0x09, 0xe6, 0x09, 0x29, 0x39); //--- #undef INTERFACE #define INTERFACE IMetaDataEmit3 DECLARE_INTERFACE_(IMetaDataEmit3, IMetaDataEmit2) { STDMETHOD(GetReferencedTypeSysTables)( // S_OK or error. ULONG64 *refTables, // [OUT] Bit vector of referenced type system metadata tables. ULONG refTableRows[], // [OUT] Array of number of rows for each referenced type system table. const ULONG maxTableRowsSize, // [IN] Max size of the rows array. ULONG *tableRowsSize) PURE; // [OUT] Actual size of the rows array. STDMETHOD(DefinePdbStream)( // S_OK or error. PORT_PDB_STREAM *pdbStream) PURE; // [IN] Portable pdb stream data. STDMETHOD(DefineDocument)( // S_OK or error. char *docName, // [IN] Document name (string will be tokenized). GUID *hashAlg, // [IN] Hash algorithm GUID. BYTE *hashVal, // [IN] Hash value. ULONG hashValSize, // [IN] Hash value size. GUID *lang, // [IN] Language GUID. mdDocument *docMdToken) PURE; // [OUT] Token of the defined document. STDMETHOD(DefineSequencePoints)( // S_OK or error. ULONG docRid, // [IN] Document RID. BYTE *sequencePtsBlob, // [IN] Sequence point blob. ULONG sequencePtsBlobSize) PURE; // [IN] Sequence point blob size. STDMETHOD(DefineLocalScope)( // S_OK or error. ULONG methodDefRid, // [IN] Method RID. ULONG importScopeRid, // [IN] Import scope RID. ULONG firstLocalVarRid, // [IN] First local variable RID (of the continous run). ULONG firstLocalConstRid, // [IN] First local constant RID (of the continous run). ULONG startOffset, // [IN] Start offset of the scope. ULONG length) PURE; // [IN] Scope length. STDMETHOD(DefineLocalVariable)( // S_OK or error. USHORT attribute, // [IN] Variable attribute. USHORT index, // [IN] Variable index (slot). char *name, // [IN] Variable name. mdLocalVariable *locVarToken) PURE; // [OUT] Token of the defined variable. }; //------------------------------------- //--- IMetaDataDispenserEx2 //------------------------------------- // {23aaef0d-49bf-43f0-9744-1c3e9c56322a} EXTERN_GUID(IID_IMetaDataDispenserEx2, 0x23aaef0d, 0x49bf, 0x43f0, 0x97, 0x44, 0x1c, 0x3e, 0x9c, 0x56, 0x32, 0x2a); #undef INTERFACE #define INTERFACE IMetaDataDispenserEx2 DECLARE_INTERFACE_(IMetaDataDispenserEx2, IMetaDataDispenserEx) { STDMETHOD(DefinePortablePdbScope)( // Return code. REFCLSID rclsid, // [IN] What version to create. DWORD dwCreateFlags, // [IN] Flags on the create. REFIID riid, // [IN] The interface desired. IUnknown * *ppIUnk) PURE; // [OUT] Return interface on success. }; #ifdef __cplusplus } #endif #endif // _PORTABLEPDBMDI_H_
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/tests/Interop/IJW/NativeVarargs/CMakeLists.txt
project (IjwNativeVarargs) include("../IJW.cmake") include_directories( ${INC_PLATFORM_DIR} ) set(SOURCES IjwNativeVarargs.cpp) # add the shared library add_library (IjwNativeVarargs SHARED ${SOURCES}) target_link_libraries(IjwNativeVarargs ${LINK_LIBRARIES_ADDITIONAL}) # add the install targets install (TARGETS IjwNativeVarargs DESTINATION bin)
project (IjwNativeVarargs) include("../IJW.cmake") include_directories( ${INC_PLATFORM_DIR} ) set(SOURCES IjwNativeVarargs.cpp) # add the shared library add_library (IjwNativeVarargs SHARED ${SOURCES}) target_link_libraries(IjwNativeVarargs ${LINK_LIBRARIES_ADDITIONAL}) # add the install targets install (TARGETS IjwNativeVarargs DESTINATION bin)
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/mono/mono/utils/mono-os-mutex.c
/** * \file * Portability wrappers around POSIX Mutexes * * Authors: Jeffrey Stedfast <[email protected]> * * Copyright 2002 Ximian, Inc. (www.ximian.com) * * Licensed under the MIT license. See LICENSE file in the project root for full license information. * */ #include <config.h> #if !defined(HOST_WIN32) #if defined(TARGET_OSX) /* So we can use the declaration of pthread_cond_timedwait_relative_np () */ #undef _XOPEN_SOURCE #endif #include <pthread.h> #include "mono-os-mutex.h" int mono_os_cond_timedwait (mono_cond_t *cond, mono_mutex_t *mutex, guint32 timeout_ms) { struct timespec ts; int res; if (timeout_ms == MONO_INFINITE_WAIT) { mono_os_cond_wait (cond, mutex); return 0; } /* ms = 10^-3, us = 10^-6, ns = 10^-9 */ /* This function only seems to be available on 64bit osx */ #if defined(HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE_NP) && defined(TARGET_OSX) memset (&ts, 0, sizeof (struct timespec)); ts.tv_sec = timeout_ms / 1000; ts.tv_nsec = (timeout_ms % 1000) * 1000 * 1000; res = pthread_cond_timedwait_relative_np (cond, mutex, &ts); if (G_UNLIKELY (res != 0 && res != ETIMEDOUT)) { g_print ("cond: %p mutex: %p\n", *(gpointer*)cond, *(gpointer*)mutex); g_error ("%s: pthread_cond_timedwait_relative_np failed with \"%s\" (%d) %ld %ld %d", __func__, g_strerror (res), res, ts.tv_sec, ts.tv_nsec, timeout_ms); } return res != 0 ? -1 : 0; #else #ifdef BROKEN_CLOCK_SOURCE struct timeval tv; /* clock_gettime is not supported in MAC OS x */ res = gettimeofday (&tv, NULL); if (G_UNLIKELY (res != 0)) g_error ("%s: gettimeofday failed with \"%s\" (%d)", __func__, g_strerror (errno), errno); ts.tv_sec = tv.tv_sec; ts.tv_nsec = tv.tv_usec * 1000; #else /* cond is using CLOCK_MONOTONIC as time source */ res = clock_gettime (CLOCK_MONOTONIC, &ts); if (G_UNLIKELY (res != 0)) g_error ("%s: clock_gettime failed with \"%s\" (%d)", __func__, g_strerror (errno), errno); #endif ts.tv_sec += timeout_ms / 1000; ts.tv_nsec += (timeout_ms % 1000) * 1000 * 1000; if (ts.tv_nsec >= 1000 * 1000 * 1000) { ts.tv_nsec -= 1000 * 1000 * 1000; ts.tv_sec ++; } res = pthread_cond_timedwait (cond, mutex, &ts); if (G_UNLIKELY (res != 0 && res != ETIMEDOUT)) { g_print ("cond: %p mutex: %p\n", *(gpointer*)cond, *(gpointer*)mutex); g_error ("%s: pthread_cond_timedwait failed with \"%s\" (%d) %ld %ld %d", __func__, g_strerror (res), res, ts.tv_sec, ts.tv_nsec, timeout_ms); } return res != 0 ? -1 : 0; #endif /* !HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE_NP */ } #endif /* HOST_WIN32 */
/** * \file * Portability wrappers around POSIX Mutexes * * Authors: Jeffrey Stedfast <[email protected]> * * Copyright 2002 Ximian, Inc. (www.ximian.com) * * Licensed under the MIT license. See LICENSE file in the project root for full license information. * */ #include <config.h> #if !defined(HOST_WIN32) #if defined(TARGET_OSX) /* So we can use the declaration of pthread_cond_timedwait_relative_np () */ #undef _XOPEN_SOURCE #endif #include <pthread.h> #include "mono-os-mutex.h" int mono_os_cond_timedwait (mono_cond_t *cond, mono_mutex_t *mutex, guint32 timeout_ms) { struct timespec ts; int res; if (timeout_ms == MONO_INFINITE_WAIT) { mono_os_cond_wait (cond, mutex); return 0; } /* ms = 10^-3, us = 10^-6, ns = 10^-9 */ /* This function only seems to be available on 64bit osx */ #if defined(HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE_NP) && defined(TARGET_OSX) memset (&ts, 0, sizeof (struct timespec)); ts.tv_sec = timeout_ms / 1000; ts.tv_nsec = (timeout_ms % 1000) * 1000 * 1000; res = pthread_cond_timedwait_relative_np (cond, mutex, &ts); if (G_UNLIKELY (res != 0 && res != ETIMEDOUT)) { g_print ("cond: %p mutex: %p\n", *(gpointer*)cond, *(gpointer*)mutex); g_error ("%s: pthread_cond_timedwait_relative_np failed with \"%s\" (%d) %ld %ld %d", __func__, g_strerror (res), res, ts.tv_sec, ts.tv_nsec, timeout_ms); } return res != 0 ? -1 : 0; #else #ifdef BROKEN_CLOCK_SOURCE struct timeval tv; /* clock_gettime is not supported in MAC OS x */ res = gettimeofday (&tv, NULL); if (G_UNLIKELY (res != 0)) g_error ("%s: gettimeofday failed with \"%s\" (%d)", __func__, g_strerror (errno), errno); ts.tv_sec = tv.tv_sec; ts.tv_nsec = tv.tv_usec * 1000; #else /* cond is using CLOCK_MONOTONIC as time source */ res = clock_gettime (CLOCK_MONOTONIC, &ts); if (G_UNLIKELY (res != 0)) g_error ("%s: clock_gettime failed with \"%s\" (%d)", __func__, g_strerror (errno), errno); #endif ts.tv_sec += timeout_ms / 1000; ts.tv_nsec += (timeout_ms % 1000) * 1000 * 1000; if (ts.tv_nsec >= 1000 * 1000 * 1000) { ts.tv_nsec -= 1000 * 1000 * 1000; ts.tv_sec ++; } res = pthread_cond_timedwait (cond, mutex, &ts); if (G_UNLIKELY (res != 0 && res != ETIMEDOUT)) { g_print ("cond: %p mutex: %p\n", *(gpointer*)cond, *(gpointer*)mutex); g_error ("%s: pthread_cond_timedwait failed with \"%s\" (%d) %ld %ld %d", __func__, g_strerror (res), res, ts.tv_sec, ts.tv_nsec, timeout_ms); } return res != 0 ? -1 : 0; #endif /* !HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE_NP */ } #endif /* HOST_WIN32 */
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/native/external/brotli/common/version.h
/* Copyright 2016 Google Inc. All Rights Reserved. Distributed under MIT license. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT */ /* Version definition. */ #ifndef BROTLI_COMMON_VERSION_H_ #define BROTLI_COMMON_VERSION_H_ /* This macro should only be used when library is compiled together with client. If library is dynamically linked, use BrotliDecoderVersion and BrotliEncoderVersion methods. */ /* Semantic version, calculated as (MAJOR << 24) | (MINOR << 12) | PATCH */ #define BROTLI_VERSION 0x1000009 /* This macro is used by build system to produce Libtool-friendly soname. See https://www.gnu.org/software/libtool/manual/html_node/Libtool-versioning.html */ /* ABI version, calculated as (CURRENT << 24) | (REVISION << 12) | AGE */ #define BROTLI_ABI_VERSION 0x1009000 #endif /* BROTLI_COMMON_VERSION_H_ */
/* Copyright 2016 Google Inc. All Rights Reserved. Distributed under MIT license. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT */ /* Version definition. */ #ifndef BROTLI_COMMON_VERSION_H_ #define BROTLI_COMMON_VERSION_H_ /* This macro should only be used when library is compiled together with client. If library is dynamically linked, use BrotliDecoderVersion and BrotliEncoderVersion methods. */ /* Semantic version, calculated as (MAJOR << 24) | (MINOR << 12) | PATCH */ #define BROTLI_VERSION 0x1000009 /* This macro is used by build system to produce Libtool-friendly soname. See https://www.gnu.org/software/libtool/manual/html_node/Libtool-versioning.html */ /* ABI version, calculated as (CURRENT << 24) | (REVISION << 12) | AGE */ #define BROTLI_ABI_VERSION 0x1009000 #endif /* BROTLI_COMMON_VERSION_H_ */
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/inc/complex.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // complex.h // // // Defines a basic complex number data type. We cannot use the standard C++ library's // complex implementation, because the CLR links to the wrong CRT. // #ifndef _COMPLEX_H_ #define _COMPLEX_H_ #include <math.h> // // Default compilation mode is /fp:precise, which disables fp intrinsics. This causes us to pull in FP stuff (sqrt,etc.) from // The CRT, and increases our download size. We don't need the extra precision this gets us, so let's switch to // the intrinsic versions. // #ifdef _MSC_VER #pragma float_control(precise, off, push) #endif class Complex { public: double r; double i; Complex() : r(0), i(0) {} Complex(double real) : r(real), i(0) {} Complex(double real, double imag) : r(real), i(imag) {} Complex(const Complex& other) : r(other.r), i(other.i) {} }; inline Complex operator+(Complex left, Complex right) { LIMITED_METHOD_CONTRACT; return Complex(left.r + right.r, left.i + right.i); } inline Complex operator-(Complex left, Complex right) { LIMITED_METHOD_CONTRACT; return Complex(left.r - right.r, left.i - right.i); } inline Complex operator*(Complex left, Complex right) { LIMITED_METHOD_CONTRACT; return Complex( left.r * right.r - left.i * right.i, left.r * right.i + left.i * right.r); } inline Complex operator/(Complex left, Complex right) { LIMITED_METHOD_CONTRACT; double denom = right.r * right.r + right.i * right.i; return Complex( (left.r * right.r + left.i * right.i) / denom, (-left.r * right.i + left.i * right.r) / denom); } inline double abs(Complex c) { LIMITED_METHOD_CONTRACT; return sqrt(c.r * c.r + c.i * c.i); } #ifdef _MSC_VER #pragma float_control(pop) #endif #endif //_COMPLEX_H_
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // complex.h // // // Defines a basic complex number data type. We cannot use the standard C++ library's // complex implementation, because the CLR links to the wrong CRT. // #ifndef _COMPLEX_H_ #define _COMPLEX_H_ #include <math.h> // // Default compilation mode is /fp:precise, which disables fp intrinsics. This causes us to pull in FP stuff (sqrt,etc.) from // The CRT, and increases our download size. We don't need the extra precision this gets us, so let's switch to // the intrinsic versions. // #ifdef _MSC_VER #pragma float_control(precise, off, push) #endif class Complex { public: double r; double i; Complex() : r(0), i(0) {} Complex(double real) : r(real), i(0) {} Complex(double real, double imag) : r(real), i(imag) {} Complex(const Complex& other) : r(other.r), i(other.i) {} }; inline Complex operator+(Complex left, Complex right) { LIMITED_METHOD_CONTRACT; return Complex(left.r + right.r, left.i + right.i); } inline Complex operator-(Complex left, Complex right) { LIMITED_METHOD_CONTRACT; return Complex(left.r - right.r, left.i - right.i); } inline Complex operator*(Complex left, Complex right) { LIMITED_METHOD_CONTRACT; return Complex( left.r * right.r - left.i * right.i, left.r * right.i + left.i * right.r); } inline Complex operator/(Complex left, Complex right) { LIMITED_METHOD_CONTRACT; double denom = right.r * right.r + right.i * right.i; return Complex( (left.r * right.r + left.i * right.i) / denom, (-left.r * right.i + left.i * right.r) / denom); } inline double abs(Complex c) { LIMITED_METHOD_CONTRACT; return sqrt(c.r * c.r + c.i * c.i); } #ifdef _MSC_VER #pragma float_control(pop) #endif #endif //_COMPLEX_H_
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/native/libs/System.Security.Cryptography.Native/pal_bignum.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "pal_types.h" #include "pal_compiler.h" #include "opensslshim.h" /* Cleans up and deletes an BIGNUM instance. Implemented by: 1) Calling BN_clear_free No-op if a is null. The given BIGNUM pointer is invalid after this call. Always succeeds. */ PALEXPORT void CryptoNative_BigNumDestroy(BIGNUM* a); /* Shims the BN_bin2bn method. */ PALEXPORT BIGNUM* CryptoNative_BigNumFromBinary(const uint8_t* s, int32_t len); /* Shims the BN_bn2bin method. */ PALEXPORT int32_t CryptoNative_BigNumToBinary(const BIGNUM* a, uint8_t* to); /* Returns the number of bytes needed to export a BIGNUM. */ PALEXPORT int32_t CryptoNative_GetBigNumBytes(const BIGNUM* a);
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "pal_types.h" #include "pal_compiler.h" #include "opensslshim.h" /* Cleans up and deletes an BIGNUM instance. Implemented by: 1) Calling BN_clear_free No-op if a is null. The given BIGNUM pointer is invalid after this call. Always succeeds. */ PALEXPORT void CryptoNative_BigNumDestroy(BIGNUM* a); /* Shims the BN_bin2bn method. */ PALEXPORT BIGNUM* CryptoNative_BigNumFromBinary(const uint8_t* s, int32_t len); /* Shims the BN_bn2bin method. */ PALEXPORT int32_t CryptoNative_BigNumToBinary(const BIGNUM* a, uint8_t* to); /* Returns the number of bytes needed to export a BIGNUM. */ PALEXPORT int32_t CryptoNative_GetBigNumBytes(const BIGNUM* a);
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/mono/mono/utils/w32subset.h
/** * \file * Define Win32 API subset defaults. * Other subsetters can fork this file, or * define symbols ahead of it, or after it (with undef). * * Note that #if of an undefined symbols is defined as if 0, * so that an implicit default here. * * Copyright 2019 Microsoft * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #ifndef HAVE_API_SUPPORT_WIN32_BSTR #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_BSTR 1 #else #define HAVE_API_SUPPORT_WIN32_BSTR 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_CANCEL_IO #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_CANCEL_IO 1 #else #define HAVE_API_SUPPORT_WIN32_CANCEL_IO 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_CANCEL_IO_EX #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_CANCEL_IO_EX 1 #else #define HAVE_API_SUPPORT_WIN32_CANCEL_IO_EX 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_CANCEL_SYNCHRONOUS_IO #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_CANCEL_SYNCHRONOUS_IO 1 #else #define HAVE_API_SUPPORT_WIN32_CANCEL_SYNCHRONOUS_IO 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_COMMAND_LINE_TO_ARGV #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_COMMAND_LINE_TO_ARGV 1 #else #define HAVE_API_SUPPORT_WIN32_COMMAND_LINE_TO_ARGV 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_CONSOLE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_CONSOLE 1 #else #define HAVE_API_SUPPORT_WIN32_CONSOLE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_COPY_FILE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_COPY_FILE 1 #else #define HAVE_API_SUPPORT_WIN32_COPY_FILE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_COPY_FILE2 #if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_COPY_FILE2 1 #else #define HAVE_API_SUPPORT_WIN32_COPY_FILE2 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_COREE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_COREE 1 #else #define HAVE_API_SUPPORT_WIN32_COREE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_CREATE_PROCESS #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_CREATE_PROCESS 1 #else #define HAVE_API_SUPPORT_WIN32_CREATE_PROCESS 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_CREATE_PROCESS_WITH_LOGON #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_CREATE_PROCESS_WITH_LOGON 1 #else #define HAVE_API_SUPPORT_WIN32_CREATE_PROCESS_WITH_LOGON 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_CREATE_SEMAPHORE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_CREATE_SEMAPHORE 1 #else #define HAVE_API_SUPPORT_WIN32_CREATE_SEMAPHORE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_CREATE_SEMAPHORE_EX #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_CREATE_SEMAPHORE_EX 1 #else #define HAVE_API_SUPPORT_WIN32_CREATE_SEMAPHORE_EX 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_DISCONNECT_EX #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_DISCONNECT_EX 1 #else #define HAVE_API_SUPPORT_WIN32_DISCONNECT_EX 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_ENUM_PROCESSES #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_ENUM_PROCESSES 1 #else #define HAVE_API_SUPPORT_WIN32_ENUM_PROCESSES 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_ENUM_PROCESS_MODULES #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_ENUM_PROCESS_MODULES 1 #else #define HAVE_API_SUPPORT_WIN32_ENUM_PROCESS_MODULES 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_ENUM_WINDOWS #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_ENUM_WINDOWS 1 #else #define HAVE_API_SUPPORT_WIN32_ENUM_WINDOWS 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_FILE_MAPPING #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_FILE_MAPPING 1 #else #define HAVE_API_SUPPORT_WIN32_FILE_MAPPING 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_FILE_MAPPING_FROM_APP #if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_FILE_MAPPING_FROM_APP 1 #else #define HAVE_API_SUPPORT_WIN32_FILE_MAPPING_FROM_APP 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_FORMAT_MESSAGE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_FORMAT_MESSAGE 1 #else #define HAVE_API_SUPPORT_WIN32_FORMAT_MESSAGE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_ACP #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_ACP 1 #else #define HAVE_API_SUPPORT_WIN32_GET_ACP 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_CP_INFO_EX #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_CP_INFO_EX 1 #else #define HAVE_API_SUPPORT_WIN32_GET_CP_INFO_EX 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_DRIVE_TYPE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_DRIVE_TYPE 1 #else #define HAVE_API_SUPPORT_WIN32_GET_DRIVE_TYPE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_FILE_SIZE_EX #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_FILE_SIZE_EX 1 #else #define HAVE_API_SUPPORT_WIN32_GET_FILE_SIZE_EX 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_FILE_VERSION_INFO #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_FILE_VERSION_INFO 1 #else #define HAVE_API_SUPPORT_WIN32_GET_FILE_VERSION_INFO 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_LOGICAL_DRIVE_STRINGS #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_LOGICAL_DRIVE_STRINGS 1 #else #define HAVE_API_SUPPORT_WIN32_GET_LOGICAL_DRIVE_STRINGS 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_MODULE_BASE_NAME #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_MODULE_BASE_NAME 1 #else #define HAVE_API_SUPPORT_WIN32_GET_MODULE_BASE_NAME 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_MODULE_FILE_NAME_EX #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_MODULE_FILE_NAME_EX 1 #else #define HAVE_API_SUPPORT_WIN32_GET_MODULE_FILE_NAME_EX 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_MODULE_HANDLE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_MODULE_HANDLE 1 #else #define HAVE_API_SUPPORT_WIN32_GET_MODULE_HANDLE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_MODULE_HANDLE_EX #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_MODULE_HANDLE_EX 1 #else #define HAVE_API_SUPPORT_WIN32_GET_MODULE_HANDLE_EX 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_MODULE_INFORMATION #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_MODULE_INFORMATION 1 #else #define HAVE_API_SUPPORT_WIN32_GET_MODULE_INFORMATION 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_PRIORITY_CLASS #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_PRIORITY_CLASS 1 #else #define HAVE_API_SUPPORT_WIN32_GET_PRIORITY_CLASS 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_PROCESS_TIMES #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_PROCESS_TIMES 1 #else #define HAVE_API_SUPPORT_WIN32_GET_PROCESS_TIMES 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_STD_HANDLE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_STD_HANDLE 1 #else #define HAVE_API_SUPPORT_WIN32_GET_STD_HANDLE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_SYSTEM_TIME_AS_FILE_TIME #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_SYSTEM_TIME_AS_FILE_TIME 1 #else #define HAVE_API_SUPPORT_WIN32_GET_SYSTEM_TIME_AS_FILE_TIME 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_SYSTEM_TIMES #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_SYSTEM_TIMES 1 #else #define HAVE_API_SUPPORT_WIN32_GET_SYSTEM_TIMES 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_WORKING_SET_SIZE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_WORKING_SET_SIZE 1 #else #define HAVE_API_SUPPORT_WIN32_GET_WORKING_SET_SIZE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_IS_WOW64_PROCESS #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_IS_WOW64_PROCESS 1 #else #define HAVE_API_SUPPORT_WIN32_IS_WOW64_PROCESS 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_LOAD_LIBRARY #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_LOAD_LIBRARY 1 #else #define HAVE_API_SUPPORT_WIN32_LOAD_LIBRARY 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_LOAD_PACKAGED_LIBRARY #if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_LOAD_PACKAGED_LIBRARY 1 #else #define HAVE_API_SUPPORT_WIN32_LOAD_PACKAGED_LIBRARY 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_LOCAL_ALLOC_FREE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_LOCAL_ALLOC_FREE 1 #else #define HAVE_API_SUPPORT_WIN32_LOCAL_ALLOC_FREE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_LOCAL_INFO #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_LOCAL_INFO 1 #else #define HAVE_API_SUPPORT_WIN32_LOCAL_INFO 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_LOCAL_INFO_EX #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_LOCAL_INFO_EX 1 #else #define HAVE_API_SUPPORT_WIN32_LOCAL_INFO_EX 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_LOCK_FILE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_LOCK_FILE 1 #else #define HAVE_API_SUPPORT_WIN32_LOCK_FILE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_MOVE_FILE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_MOVE_FILE 1 #else #define HAVE_API_SUPPORT_WIN32_MOVE_FILE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_MOVE_FILE_EX #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_MOVE_FILE_EX 1 #else #define HAVE_API_SUPPORT_WIN32_MOVE_FILE_EX 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_MSG_WAIT_FOR_MULTIPLE_OBJECTS #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_MSG_WAIT_FOR_MULTIPLE_OBJECTS 1 #else #define HAVE_API_SUPPORT_WIN32_MSG_WAIT_FOR_MULTIPLE_OBJECTS 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_OPEN_PROCESS #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_OPEN_PROCESS 1 #else #define HAVE_API_SUPPORT_WIN32_OPEN_PROCESS 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_OPEN_THREAD #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_OPEN_THREAD 1 #else #define HAVE_API_SUPPORT_WIN32_OPEN_THREAD 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_REPLACE_FILE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_REPLACE_FILE 1 #else #define HAVE_API_SUPPORT_WIN32_REPLACE_FILE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_RESET_STKOFLW #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_RESET_STKOFLW 1 #else #define HAVE_API_SUPPORT_WIN32_RESET_STKOFLW 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_SAFE_ARRAY #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_SAFE_ARRAY 1 #else #define HAVE_API_SUPPORT_WIN32_SAFE_ARRAY 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_SET_ERROR_MODE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_SET_ERROR_MODE 1 #else #define HAVE_API_SUPPORT_WIN32_SET_ERROR_MODE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_SET_PRIORITY_CLASS #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_SET_PRIORITY_CLASS 1 #else #define HAVE_API_SUPPORT_WIN32_SET_PRIORITY_CLASS 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_SET_THREAD_CONTEXT #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_SET_THREAD_CONTEXT 1 #else #define HAVE_API_SUPPORT_WIN32_SET_THREAD_CONTEXT 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_SET_THREAD_DESCRIPTION #if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_SET_THREAD_DESCRIPTION 1 #else #define HAVE_API_SUPPORT_WIN32_SET_THREAD_DESCRIPTION 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_SET_THREAD_STACK_GUARANTEE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_SET_THREAD_STACK_GUARANTEE 1 #else #define HAVE_API_SUPPORT_WIN32_SET_THREAD_STACK_GUARANTEE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_SET_WORKING_SET_SIZE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_SET_WORKING_SET_SIZE 1 #else #define HAVE_API_SUPPORT_WIN32_SET_WORKING_SET_SIZE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_SHELL_EXECUTE_EX #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_SHELL_EXECUTE_EX 1 #else #define HAVE_API_SUPPORT_WIN32_SHELL_EXECUTE_EX 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_SIGNAL_OBJECT_AND_WAIT #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_SIGNAL_OBJECT_AND_WAIT 1 #else #define HAVE_API_SUPPORT_WIN32_SIGNAL_OBJECT_AND_WAIT 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_TIMERS #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_TIMERS 1 #else #define HAVE_API_SUPPORT_WIN32_TIMERS 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_TRANSMIT_FILE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_TRANSMIT_FILE 1 #else #define HAVE_API_SUPPORT_WIN32_TRANSMIT_FILE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_UNLOCK_FILE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_UNLOCK_FILE 1 #else #define HAVE_API_SUPPORT_WIN32_UNLOCK_FILE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_VER_LANGUAGE_NAME #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_VER_LANGUAGE_NAME 1 #else #define HAVE_API_SUPPORT_WIN32_VER_LANGUAGE_NAME 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_VER_QUERY_VALUE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_VER_QUERY_VALUE 1 #else #define HAVE_API_SUPPORT_WIN32_VER_QUERY_VALUE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_PIPE_OPEN_CLOSE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_PIPE_OPEN_CLOSE 1 #else #define HAVE_API_SUPPORT_WIN32_PIPE_OPEN_CLOSE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_CONTEXT_XSTATE #define HAVE_API_SUPPORT_WIN32_CONTEXT_XSTATE 0 #endif
/** * \file * Define Win32 API subset defaults. * Other subsetters can fork this file, or * define symbols ahead of it, or after it (with undef). * * Note that #if of an undefined symbols is defined as if 0, * so that an implicit default here. * * Copyright 2019 Microsoft * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #ifndef HAVE_API_SUPPORT_WIN32_BSTR #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_BSTR 1 #else #define HAVE_API_SUPPORT_WIN32_BSTR 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_CANCEL_IO #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_CANCEL_IO 1 #else #define HAVE_API_SUPPORT_WIN32_CANCEL_IO 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_CANCEL_IO_EX #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_CANCEL_IO_EX 1 #else #define HAVE_API_SUPPORT_WIN32_CANCEL_IO_EX 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_CANCEL_SYNCHRONOUS_IO #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_CANCEL_SYNCHRONOUS_IO 1 #else #define HAVE_API_SUPPORT_WIN32_CANCEL_SYNCHRONOUS_IO 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_COMMAND_LINE_TO_ARGV #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_COMMAND_LINE_TO_ARGV 1 #else #define HAVE_API_SUPPORT_WIN32_COMMAND_LINE_TO_ARGV 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_CONSOLE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_CONSOLE 1 #else #define HAVE_API_SUPPORT_WIN32_CONSOLE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_COPY_FILE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_COPY_FILE 1 #else #define HAVE_API_SUPPORT_WIN32_COPY_FILE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_COPY_FILE2 #if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_COPY_FILE2 1 #else #define HAVE_API_SUPPORT_WIN32_COPY_FILE2 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_COREE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_COREE 1 #else #define HAVE_API_SUPPORT_WIN32_COREE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_CREATE_PROCESS #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_CREATE_PROCESS 1 #else #define HAVE_API_SUPPORT_WIN32_CREATE_PROCESS 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_CREATE_PROCESS_WITH_LOGON #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_CREATE_PROCESS_WITH_LOGON 1 #else #define HAVE_API_SUPPORT_WIN32_CREATE_PROCESS_WITH_LOGON 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_CREATE_SEMAPHORE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_CREATE_SEMAPHORE 1 #else #define HAVE_API_SUPPORT_WIN32_CREATE_SEMAPHORE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_CREATE_SEMAPHORE_EX #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_CREATE_SEMAPHORE_EX 1 #else #define HAVE_API_SUPPORT_WIN32_CREATE_SEMAPHORE_EX 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_DISCONNECT_EX #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_DISCONNECT_EX 1 #else #define HAVE_API_SUPPORT_WIN32_DISCONNECT_EX 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_ENUM_PROCESSES #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_ENUM_PROCESSES 1 #else #define HAVE_API_SUPPORT_WIN32_ENUM_PROCESSES 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_ENUM_PROCESS_MODULES #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_ENUM_PROCESS_MODULES 1 #else #define HAVE_API_SUPPORT_WIN32_ENUM_PROCESS_MODULES 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_ENUM_WINDOWS #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_ENUM_WINDOWS 1 #else #define HAVE_API_SUPPORT_WIN32_ENUM_WINDOWS 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_FILE_MAPPING #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_FILE_MAPPING 1 #else #define HAVE_API_SUPPORT_WIN32_FILE_MAPPING 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_FILE_MAPPING_FROM_APP #if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_FILE_MAPPING_FROM_APP 1 #else #define HAVE_API_SUPPORT_WIN32_FILE_MAPPING_FROM_APP 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_FORMAT_MESSAGE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_FORMAT_MESSAGE 1 #else #define HAVE_API_SUPPORT_WIN32_FORMAT_MESSAGE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_ACP #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_ACP 1 #else #define HAVE_API_SUPPORT_WIN32_GET_ACP 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_CP_INFO_EX #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_CP_INFO_EX 1 #else #define HAVE_API_SUPPORT_WIN32_GET_CP_INFO_EX 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_DRIVE_TYPE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_DRIVE_TYPE 1 #else #define HAVE_API_SUPPORT_WIN32_GET_DRIVE_TYPE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_FILE_SIZE_EX #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_FILE_SIZE_EX 1 #else #define HAVE_API_SUPPORT_WIN32_GET_FILE_SIZE_EX 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_FILE_VERSION_INFO #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_FILE_VERSION_INFO 1 #else #define HAVE_API_SUPPORT_WIN32_GET_FILE_VERSION_INFO 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_LOGICAL_DRIVE_STRINGS #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_LOGICAL_DRIVE_STRINGS 1 #else #define HAVE_API_SUPPORT_WIN32_GET_LOGICAL_DRIVE_STRINGS 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_MODULE_BASE_NAME #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_MODULE_BASE_NAME 1 #else #define HAVE_API_SUPPORT_WIN32_GET_MODULE_BASE_NAME 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_MODULE_FILE_NAME_EX #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_MODULE_FILE_NAME_EX 1 #else #define HAVE_API_SUPPORT_WIN32_GET_MODULE_FILE_NAME_EX 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_MODULE_HANDLE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_MODULE_HANDLE 1 #else #define HAVE_API_SUPPORT_WIN32_GET_MODULE_HANDLE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_MODULE_HANDLE_EX #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_MODULE_HANDLE_EX 1 #else #define HAVE_API_SUPPORT_WIN32_GET_MODULE_HANDLE_EX 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_MODULE_INFORMATION #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_MODULE_INFORMATION 1 #else #define HAVE_API_SUPPORT_WIN32_GET_MODULE_INFORMATION 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_PRIORITY_CLASS #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_PRIORITY_CLASS 1 #else #define HAVE_API_SUPPORT_WIN32_GET_PRIORITY_CLASS 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_PROCESS_TIMES #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_PROCESS_TIMES 1 #else #define HAVE_API_SUPPORT_WIN32_GET_PROCESS_TIMES 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_STD_HANDLE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_STD_HANDLE 1 #else #define HAVE_API_SUPPORT_WIN32_GET_STD_HANDLE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_SYSTEM_TIME_AS_FILE_TIME #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_SYSTEM_TIME_AS_FILE_TIME 1 #else #define HAVE_API_SUPPORT_WIN32_GET_SYSTEM_TIME_AS_FILE_TIME 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_SYSTEM_TIMES #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_SYSTEM_TIMES 1 #else #define HAVE_API_SUPPORT_WIN32_GET_SYSTEM_TIMES 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_GET_WORKING_SET_SIZE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_GET_WORKING_SET_SIZE 1 #else #define HAVE_API_SUPPORT_WIN32_GET_WORKING_SET_SIZE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_IS_WOW64_PROCESS #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_IS_WOW64_PROCESS 1 #else #define HAVE_API_SUPPORT_WIN32_IS_WOW64_PROCESS 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_LOAD_LIBRARY #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_LOAD_LIBRARY 1 #else #define HAVE_API_SUPPORT_WIN32_LOAD_LIBRARY 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_LOAD_PACKAGED_LIBRARY #if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_LOAD_PACKAGED_LIBRARY 1 #else #define HAVE_API_SUPPORT_WIN32_LOAD_PACKAGED_LIBRARY 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_LOCAL_ALLOC_FREE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_LOCAL_ALLOC_FREE 1 #else #define HAVE_API_SUPPORT_WIN32_LOCAL_ALLOC_FREE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_LOCAL_INFO #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_LOCAL_INFO 1 #else #define HAVE_API_SUPPORT_WIN32_LOCAL_INFO 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_LOCAL_INFO_EX #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_LOCAL_INFO_EX 1 #else #define HAVE_API_SUPPORT_WIN32_LOCAL_INFO_EX 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_LOCK_FILE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_LOCK_FILE 1 #else #define HAVE_API_SUPPORT_WIN32_LOCK_FILE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_MOVE_FILE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_MOVE_FILE 1 #else #define HAVE_API_SUPPORT_WIN32_MOVE_FILE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_MOVE_FILE_EX #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_MOVE_FILE_EX 1 #else #define HAVE_API_SUPPORT_WIN32_MOVE_FILE_EX 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_MSG_WAIT_FOR_MULTIPLE_OBJECTS #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_MSG_WAIT_FOR_MULTIPLE_OBJECTS 1 #else #define HAVE_API_SUPPORT_WIN32_MSG_WAIT_FOR_MULTIPLE_OBJECTS 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_OPEN_PROCESS #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_OPEN_PROCESS 1 #else #define HAVE_API_SUPPORT_WIN32_OPEN_PROCESS 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_OPEN_THREAD #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_OPEN_THREAD 1 #else #define HAVE_API_SUPPORT_WIN32_OPEN_THREAD 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_REPLACE_FILE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_REPLACE_FILE 1 #else #define HAVE_API_SUPPORT_WIN32_REPLACE_FILE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_RESET_STKOFLW #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_RESET_STKOFLW 1 #else #define HAVE_API_SUPPORT_WIN32_RESET_STKOFLW 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_SAFE_ARRAY #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_SAFE_ARRAY 1 #else #define HAVE_API_SUPPORT_WIN32_SAFE_ARRAY 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_SET_ERROR_MODE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_SET_ERROR_MODE 1 #else #define HAVE_API_SUPPORT_WIN32_SET_ERROR_MODE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_SET_PRIORITY_CLASS #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_SET_PRIORITY_CLASS 1 #else #define HAVE_API_SUPPORT_WIN32_SET_PRIORITY_CLASS 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_SET_THREAD_CONTEXT #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_SET_THREAD_CONTEXT 1 #else #define HAVE_API_SUPPORT_WIN32_SET_THREAD_CONTEXT 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_SET_THREAD_DESCRIPTION #if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_SET_THREAD_DESCRIPTION 1 #else #define HAVE_API_SUPPORT_WIN32_SET_THREAD_DESCRIPTION 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_SET_THREAD_STACK_GUARANTEE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_SET_THREAD_STACK_GUARANTEE 1 #else #define HAVE_API_SUPPORT_WIN32_SET_THREAD_STACK_GUARANTEE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_SET_WORKING_SET_SIZE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_SET_WORKING_SET_SIZE 1 #else #define HAVE_API_SUPPORT_WIN32_SET_WORKING_SET_SIZE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_SHELL_EXECUTE_EX #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_SHELL_EXECUTE_EX 1 #else #define HAVE_API_SUPPORT_WIN32_SHELL_EXECUTE_EX 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_SIGNAL_OBJECT_AND_WAIT #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_SIGNAL_OBJECT_AND_WAIT 1 #else #define HAVE_API_SUPPORT_WIN32_SIGNAL_OBJECT_AND_WAIT 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_TIMERS #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_TIMERS 1 #else #define HAVE_API_SUPPORT_WIN32_TIMERS 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_TRANSMIT_FILE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_TRANSMIT_FILE 1 #else #define HAVE_API_SUPPORT_WIN32_TRANSMIT_FILE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_UNLOCK_FILE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) || \ G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_UNLOCK_FILE 1 #else #define HAVE_API_SUPPORT_WIN32_UNLOCK_FILE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_VER_LANGUAGE_NAME #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_VER_LANGUAGE_NAME 1 #else #define HAVE_API_SUPPORT_WIN32_VER_LANGUAGE_NAME 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_VER_QUERY_VALUE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_VER_QUERY_VALUE 1 #else #define HAVE_API_SUPPORT_WIN32_VER_QUERY_VALUE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_PIPE_OPEN_CLOSE #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) #define HAVE_API_SUPPORT_WIN32_PIPE_OPEN_CLOSE 1 #else #define HAVE_API_SUPPORT_WIN32_PIPE_OPEN_CLOSE 0 #endif #endif #ifndef HAVE_API_SUPPORT_WIN32_CONTEXT_XSTATE #define HAVE_API_SUPPORT_WIN32_CONTEXT_XSTATE 0 #endif
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/native/libs/System.Globalization.Native/configure.cmake
if(CLR_CMAKE_TARGET_ANDROID OR CLR_CMAKE_TARGET_OSX OR CLR_CMAKE_TARGET_MACCATALYST) set(HAVE_SET_MAX_VARIABLE 1) set(HAVE_UDAT_STANDALONE_SHORTER_WEEKDAYS 1) else() include(CheckCSourceCompiles) include(CheckSymbolExists) if (CLR_CMAKE_TARGET_UNIX) set(CMAKE_REQUIRED_INCLUDES ${UCURR_H} ${ICU_HOMEBREW_INC_PATH}) CHECK_C_SOURCE_COMPILES(" #include <unicode/udat.h> int main(void) { enum UDateFormatSymbolType e = UDAT_STANDALONE_SHORTER_WEEKDAYS; } " HAVE_UDAT_STANDALONE_SHORTER_WEEKDAYS) set(CMAKE_REQUIRED_LIBRARIES ${ICUUC} ${ICUI18N}) check_symbol_exists( ucol_setMaxVariable "unicode/ucol.h" HAVE_SET_MAX_VARIABLE) unset(CMAKE_REQUIRED_LIBRARIES) unset(CMAKE_REQUIRED_INCLUDES) endif() endif() configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/config.h.in ${CMAKE_CURRENT_BINARY_DIR}/config.h)
if(CLR_CMAKE_TARGET_ANDROID OR CLR_CMAKE_TARGET_OSX OR CLR_CMAKE_TARGET_MACCATALYST) set(HAVE_SET_MAX_VARIABLE 1) set(HAVE_UDAT_STANDALONE_SHORTER_WEEKDAYS 1) else() include(CheckCSourceCompiles) include(CheckSymbolExists) if (CLR_CMAKE_TARGET_UNIX) set(CMAKE_REQUIRED_INCLUDES ${UCURR_H} ${ICU_HOMEBREW_INC_PATH}) CHECK_C_SOURCE_COMPILES(" #include <unicode/udat.h> int main(void) { enum UDateFormatSymbolType e = UDAT_STANDALONE_SHORTER_WEEKDAYS; } " HAVE_UDAT_STANDALONE_SHORTER_WEEKDAYS) set(CMAKE_REQUIRED_LIBRARIES ${ICUUC} ${ICUI18N}) check_symbol_exists( ucol_setMaxVariable "unicode/ucol.h" HAVE_SET_MAX_VARIABLE) unset(CMAKE_REQUIRED_LIBRARIES) unset(CMAKE_REQUIRED_INCLUDES) endif() endif() configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/config.h.in ${CMAKE_CURRENT_BINARY_DIR}/config.h)
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/pal/src/libunwind/src/hppa/Ginit_remote.c
/* libunwind - a platform-independent unwind library Copyright (c) 2004 Hewlett-Packard Development Company, L.P. Contributed by David Mosberger-Tang <[email protected]> This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "init.h" #include "unwind_i.h" int unw_init_remote (unw_cursor_t *cursor, unw_addr_space_t as, void *as_arg) { #ifdef UNW_LOCAL_ONLY return -UNW_EINVAL; #else /* !UNW_LOCAL_ONLY */ struct cursor *c = (struct cursor *) cursor; if (!atomic_load(&tdep_init_done)) tdep_init (); Debug (1, "(cursor=%p)\n", c); c->dwarf.as = as; c->dwarf.as_arg = as_arg; return common_init (c, 0); #endif /* !UNW_LOCAL_ONLY */ }
/* libunwind - a platform-independent unwind library Copyright (c) 2004 Hewlett-Packard Development Company, L.P. Contributed by David Mosberger-Tang <[email protected]> This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "init.h" #include "unwind_i.h" int unw_init_remote (unw_cursor_t *cursor, unw_addr_space_t as, void *as_arg) { #ifdef UNW_LOCAL_ONLY return -UNW_EINVAL; #else /* !UNW_LOCAL_ONLY */ struct cursor *c = (struct cursor *) cursor; if (!atomic_load(&tdep_init_done)) tdep_init (); Debug (1, "(cursor=%p)\n", c); c->dwarf.as = as; c->dwarf.as_arg = as_arg; return common_init (c, 0); #endif /* !UNW_LOCAL_ONLY */ }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/native/external/rapidjson/stream.h
// Tencent is pleased to support the open source community by making RapidJSON available. // // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. // // Licensed under the MIT License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://opensource.org/licenses/MIT // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #include "rapidjson.h" #ifndef RAPIDJSON_STREAM_H_ #define RAPIDJSON_STREAM_H_ #include "encodings.h" RAPIDJSON_NAMESPACE_BEGIN /////////////////////////////////////////////////////////////////////////////// // Stream /*! \class rapidjson::Stream \brief Concept for reading and writing characters. For read-only stream, no need to implement PutBegin(), Put(), Flush() and PutEnd(). For write-only stream, only need to implement Put() and Flush(). \code concept Stream { typename Ch; //!< Character type of the stream. //! Read the current character from stream without moving the read cursor. Ch Peek() const; //! Read the current character from stream and moving the read cursor to next character. Ch Take(); //! Get the current read cursor. //! \return Number of characters read from start. size_t Tell(); //! Begin writing operation at the current read pointer. //! \return The begin writer pointer. Ch* PutBegin(); //! Write a character. void Put(Ch c); //! Flush the buffer. void Flush(); //! End the writing operation. //! \param begin The begin write pointer returned by PutBegin(). //! \return Number of characters written. size_t PutEnd(Ch* begin); } \endcode */ //! Provides additional information for stream. /*! By using traits pattern, this type provides a default configuration for stream. For custom stream, this type can be specialized for other configuration. See TEST(Reader, CustomStringStream) in readertest.cpp for example. */ template<typename Stream> struct StreamTraits { //! Whether to make local copy of stream for optimization during parsing. /*! By default, for safety, streams do not use local copy optimization. Stream that can be copied fast should specialize this, like StreamTraits<StringStream>. */ enum { copyOptimization = 0 }; }; //! Reserve n characters for writing to a stream. template<typename Stream> inline void PutReserve(Stream& stream, size_t count) { (void)stream; (void)count; } //! Write character to a stream, presuming buffer is reserved. template<typename Stream> inline void PutUnsafe(Stream& stream, typename Stream::Ch c) { stream.Put(c); } //! Put N copies of a character to a stream. template<typename Stream, typename Ch> inline void PutN(Stream& stream, Ch c, size_t n) { PutReserve(stream, n); for (size_t i = 0; i < n; i++) PutUnsafe(stream, c); } /////////////////////////////////////////////////////////////////////////////// // GenericStreamWrapper //! A Stream Wrapper /*! \tThis string stream is a wrapper for any stream by just forwarding any \treceived message to the origin stream. \note implements Stream concept */ #if defined(_MSC_VER) && _MSC_VER <= 1800 RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(4702) // unreachable code RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated #endif template <typename InputStream, typename Encoding = UTF8<> > class GenericStreamWrapper { public: typedef typename Encoding::Ch Ch; GenericStreamWrapper(InputStream& is): is_(is) {} Ch Peek() const { return is_.Peek(); } Ch Take() { return is_.Take(); } size_t Tell() { return is_.Tell(); } Ch* PutBegin() { return is_.PutBegin(); } void Put(Ch ch) { is_.Put(ch); } void Flush() { is_.Flush(); } size_t PutEnd(Ch* ch) { return is_.PutEnd(ch); } // wrapper for MemoryStream const Ch* Peek4() const { return is_.Peek4(); } // wrapper for AutoUTFInputStream UTFType GetType() const { return is_.GetType(); } bool HasBOM() const { return is_.HasBOM(); } protected: InputStream& is_; }; #if defined(_MSC_VER) && _MSC_VER <= 1800 RAPIDJSON_DIAG_POP #endif /////////////////////////////////////////////////////////////////////////////// // StringStream //! Read-only string stream. /*! \note implements Stream concept */ template <typename Encoding> struct GenericStringStream { typedef typename Encoding::Ch Ch; GenericStringStream(const Ch *src) : src_(src), head_(src) {} Ch Peek() const { return *src_; } Ch Take() { return *src_++; } size_t Tell() const { return static_cast<size_t>(src_ - head_); } Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } void Put(Ch) { RAPIDJSON_ASSERT(false); } void Flush() { RAPIDJSON_ASSERT(false); } size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; } const Ch* src_; //!< Current read position. const Ch* head_; //!< Original head of the string. }; template <typename Encoding> struct StreamTraits<GenericStringStream<Encoding> > { enum { copyOptimization = 1 }; }; //! String stream with UTF8 encoding. typedef GenericStringStream<UTF8<> > StringStream; /////////////////////////////////////////////////////////////////////////////// // InsituStringStream //! A read-write string stream. /*! This string stream is particularly designed for in-situ parsing. \note implements Stream concept */ template <typename Encoding> struct GenericInsituStringStream { typedef typename Encoding::Ch Ch; GenericInsituStringStream(Ch *src) : src_(src), dst_(0), head_(src) {} // Read Ch Peek() { return *src_; } Ch Take() { return *src_++; } size_t Tell() { return static_cast<size_t>(src_ - head_); } // Write void Put(Ch c) { RAPIDJSON_ASSERT(dst_ != 0); *dst_++ = c; } Ch* PutBegin() { return dst_ = src_; } size_t PutEnd(Ch* begin) { return static_cast<size_t>(dst_ - begin); } void Flush() {} Ch* Push(size_t count) { Ch* begin = dst_; dst_ += count; return begin; } void Pop(size_t count) { dst_ -= count; } Ch* src_; Ch* dst_; Ch* head_; }; template <typename Encoding> struct StreamTraits<GenericInsituStringStream<Encoding> > { enum { copyOptimization = 1 }; }; //! Insitu string stream with UTF8 encoding. typedef GenericInsituStringStream<UTF8<> > InsituStringStream; RAPIDJSON_NAMESPACE_END #endif // RAPIDJSON_STREAM_H_
// Tencent is pleased to support the open source community by making RapidJSON available. // // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. // // Licensed under the MIT License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://opensource.org/licenses/MIT // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #include "rapidjson.h" #ifndef RAPIDJSON_STREAM_H_ #define RAPIDJSON_STREAM_H_ #include "encodings.h" RAPIDJSON_NAMESPACE_BEGIN /////////////////////////////////////////////////////////////////////////////// // Stream /*! \class rapidjson::Stream \brief Concept for reading and writing characters. For read-only stream, no need to implement PutBegin(), Put(), Flush() and PutEnd(). For write-only stream, only need to implement Put() and Flush(). \code concept Stream { typename Ch; //!< Character type of the stream. //! Read the current character from stream without moving the read cursor. Ch Peek() const; //! Read the current character from stream and moving the read cursor to next character. Ch Take(); //! Get the current read cursor. //! \return Number of characters read from start. size_t Tell(); //! Begin writing operation at the current read pointer. //! \return The begin writer pointer. Ch* PutBegin(); //! Write a character. void Put(Ch c); //! Flush the buffer. void Flush(); //! End the writing operation. //! \param begin The begin write pointer returned by PutBegin(). //! \return Number of characters written. size_t PutEnd(Ch* begin); } \endcode */ //! Provides additional information for stream. /*! By using traits pattern, this type provides a default configuration for stream. For custom stream, this type can be specialized for other configuration. See TEST(Reader, CustomStringStream) in readertest.cpp for example. */ template<typename Stream> struct StreamTraits { //! Whether to make local copy of stream for optimization during parsing. /*! By default, for safety, streams do not use local copy optimization. Stream that can be copied fast should specialize this, like StreamTraits<StringStream>. */ enum { copyOptimization = 0 }; }; //! Reserve n characters for writing to a stream. template<typename Stream> inline void PutReserve(Stream& stream, size_t count) { (void)stream; (void)count; } //! Write character to a stream, presuming buffer is reserved. template<typename Stream> inline void PutUnsafe(Stream& stream, typename Stream::Ch c) { stream.Put(c); } //! Put N copies of a character to a stream. template<typename Stream, typename Ch> inline void PutN(Stream& stream, Ch c, size_t n) { PutReserve(stream, n); for (size_t i = 0; i < n; i++) PutUnsafe(stream, c); } /////////////////////////////////////////////////////////////////////////////// // GenericStreamWrapper //! A Stream Wrapper /*! \tThis string stream is a wrapper for any stream by just forwarding any \treceived message to the origin stream. \note implements Stream concept */ #if defined(_MSC_VER) && _MSC_VER <= 1800 RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(4702) // unreachable code RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated #endif template <typename InputStream, typename Encoding = UTF8<> > class GenericStreamWrapper { public: typedef typename Encoding::Ch Ch; GenericStreamWrapper(InputStream& is): is_(is) {} Ch Peek() const { return is_.Peek(); } Ch Take() { return is_.Take(); } size_t Tell() { return is_.Tell(); } Ch* PutBegin() { return is_.PutBegin(); } void Put(Ch ch) { is_.Put(ch); } void Flush() { is_.Flush(); } size_t PutEnd(Ch* ch) { return is_.PutEnd(ch); } // wrapper for MemoryStream const Ch* Peek4() const { return is_.Peek4(); } // wrapper for AutoUTFInputStream UTFType GetType() const { return is_.GetType(); } bool HasBOM() const { return is_.HasBOM(); } protected: InputStream& is_; }; #if defined(_MSC_VER) && _MSC_VER <= 1800 RAPIDJSON_DIAG_POP #endif /////////////////////////////////////////////////////////////////////////////// // StringStream //! Read-only string stream. /*! \note implements Stream concept */ template <typename Encoding> struct GenericStringStream { typedef typename Encoding::Ch Ch; GenericStringStream(const Ch *src) : src_(src), head_(src) {} Ch Peek() const { return *src_; } Ch Take() { return *src_++; } size_t Tell() const { return static_cast<size_t>(src_ - head_); } Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } void Put(Ch) { RAPIDJSON_ASSERT(false); } void Flush() { RAPIDJSON_ASSERT(false); } size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; } const Ch* src_; //!< Current read position. const Ch* head_; //!< Original head of the string. }; template <typename Encoding> struct StreamTraits<GenericStringStream<Encoding> > { enum { copyOptimization = 1 }; }; //! String stream with UTF8 encoding. typedef GenericStringStream<UTF8<> > StringStream; /////////////////////////////////////////////////////////////////////////////// // InsituStringStream //! A read-write string stream. /*! This string stream is particularly designed for in-situ parsing. \note implements Stream concept */ template <typename Encoding> struct GenericInsituStringStream { typedef typename Encoding::Ch Ch; GenericInsituStringStream(Ch *src) : src_(src), dst_(0), head_(src) {} // Read Ch Peek() { return *src_; } Ch Take() { return *src_++; } size_t Tell() { return static_cast<size_t>(src_ - head_); } // Write void Put(Ch c) { RAPIDJSON_ASSERT(dst_ != 0); *dst_++ = c; } Ch* PutBegin() { return dst_ = src_; } size_t PutEnd(Ch* begin) { return static_cast<size_t>(dst_ - begin); } void Flush() {} Ch* Push(size_t count) { Ch* begin = dst_; dst_ += count; return begin; } void Pop(size_t count) { dst_ -= count; } Ch* src_; Ch* dst_; Ch* head_; }; template <typename Encoding> struct StreamTraits<GenericInsituStringStream<Encoding> > { enum { copyOptimization = 1 }; }; //! Insitu string stream with UTF8 encoding. typedef GenericInsituStringStream<UTF8<> > InsituStringStream; RAPIDJSON_NAMESPACE_END #endif // RAPIDJSON_STREAM_H_
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/native/libs/System.Security.Cryptography.Native/pal_x509.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "opensslshim.h" #include "pal_compiler.h" #include "pal_crypto_types.h" /* These values should be kept in sync with System.Security.Cryptography.X509Certificates.X509RevocationFlag. */ typedef enum { EndCertificateOnly = 0, EntireChain = 1, ExcludeRoot = 2, } X509RevocationFlag; /* The error codes used when verifying X509 certificate chains. These values should be kept in sync with Interop.Crypto.X509VerifyStatusCodeUniversal. Codes specific to specific versions of OpenSSL can also be returned, but are not represented in this enum due to their non-constant nature. */ typedef enum { PAL_X509_V_OK = 0, PAL_X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT = 2, PAL_X509_V_ERR_UNABLE_TO_GET_CRL = 3, PAL_X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE = 5, PAL_X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY = 6, PAL_X509_V_ERR_CERT_SIGNATURE_FAILURE = 7, PAL_X509_V_ERR_CRL_SIGNATURE_FAILURE = 8, PAL_X509_V_ERR_CERT_NOT_YET_VALID = 9, PAL_X509_V_ERR_CERT_HAS_EXPIRED = 10, PAL_X509_V_ERR_CRL_NOT_YET_VALID = 11, PAL_X509_V_ERR_CRL_HAS_EXPIRED = 12, PAL_X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD = 13, PAL_X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD = 14, PAL_X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD = 15, PAL_X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD = 16, PAL_X509_V_ERR_OUT_OF_MEM = 17, PAL_X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT = 18, PAL_X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN = 19, PAL_X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY = 20, PAL_X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE = 21, PAL_X509_V_ERR_CERT_CHAIN_TOO_LONG = 22, PAL_X509_V_ERR_CERT_REVOKED = 23, // Code 24 varies PAL_X509_V_ERR_PATH_LENGTH_EXCEEDED = 25, PAL_X509_V_ERR_INVALID_PURPOSE = 26, PAL_X509_V_ERR_CERT_UNTRUSTED = 27, PAL_X509_V_ERR_CERT_REJECTED = 28, PAL_X509_V_ERR_KEYUSAGE_NO_CERTSIGN = 32, PAL_X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER = 33, PAL_X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION = 34, PAL_X509_V_ERR_KEYUSAGE_NO_CRL_SIGN = 35, PAL_X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION = 36, PAL_X509_V_ERR_INVALID_NON_CA = 37, PAL_X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE = 39, PAL_X509_V_ERR_INVALID_EXTENSION = 41, PAL_X509_V_ERR_INVALID_POLICY_EXTENSION = 42, PAL_X509_V_ERR_NO_EXPLICIT_POLICY = 43, PAL_X509_V_ERR_DIFFERENT_CRL_SCOPE = 44, PAL_X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE = 45, PAL_X509_V_ERR_UNNESTED_RESOURCE = 46, PAL_X509_V_ERR_PERMITTED_VIOLATION = 47, PAL_X509_V_ERR_EXCLUDED_VIOLATION = 48, PAL_X509_V_ERR_SUBTREE_MINMAX = 49, PAL_X509_V_ERR_APPLICATION_VERIFICATION = 50, PAL_X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE = 51, PAL_X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX = 52, PAL_X509_V_ERR_UNSUPPORTED_NAME_SYNTAX = 53, PAL_X509_V_ERR_CRL_PATH_VALIDATION_ERROR = 54, PAL_X509_V_ERR_SUITE_B_INVALID_VERSION = 56, PAL_X509_V_ERR_SUITE_B_INVALID_ALGORITHM = 57, PAL_X509_V_ERR_SUITE_B_INVALID_CURVE = 58, PAL_X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM = 59, PAL_X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED = 60, PAL_X509_V_ERR_SUITE_B_CANNOT_SIGN_P_384_WITH_P_256 = 61, PAL_X509_V_ERR_HOSTNAME_MISMATCH = 62, PAL_X509_V_ERR_EMAIL_MISMATCH = 63, PAL_X509_V_ERR_IP_ADDRESS_MISMATCH = 64, } X509VerifyStatusCode; typedef int32_t (*X509StoreVerifyCallback)(int32_t, X509_STORE_CTX*); /* Function: GetX509EvpPublicKey Returns a EVP_PKEY* equivalent to the public key of the certificate. */ PALEXPORT EVP_PKEY* CryptoNative_GetX509EvpPublicKey(X509* x509); /* Shims the d2i_X509_CRL method and makes it easier to invoke from managed code. */ PALEXPORT X509_CRL* CryptoNative_DecodeX509Crl(const uint8_t* buf, int32_t len); /* Shims the d2i_X509 method and makes it easier to invoke from managed code. */ PALEXPORT X509* CryptoNative_DecodeX509(const uint8_t* buf, int32_t len); /* Returns the number of bytes it will take to convert the X509 to a DER format. */ PALEXPORT int32_t CryptoNative_GetX509DerSize(X509* x); /* Shims the i2d_X509 method. Returns the number of bytes written to buf. */ PALEXPORT int32_t CryptoNative_EncodeX509(X509* x, uint8_t* buf); /* Cleans up and deletes an X509 instance. Implemented by calling X509_free. No-op if a is null. The given X509 pointer is invalid after this call. Always succeeds. */ PALEXPORT void CryptoNative_X509Destroy(X509* a); /* Shims the X509_dup method. Returns the duplicated X509 instance. */ PALEXPORT X509* CryptoNative_X509Duplicate(X509* x509); /* Shims the PEM_read_bio_X509 method. Returns the read X509 instance. */ PALEXPORT X509* CryptoNative_PemReadX509FromBio(BIO* bio); /* Shims the PEM_read_bio_X509_AUX method. Returns the read X509 instance. */ PALEXPORT X509* CryptoNative_PemReadX509FromBioAux(BIO* bio); /* Shims the X509_get_serialNumber method. Returns the ASN1_INTEGER for the serial number. */ PALEXPORT ASN1_INTEGER* CryptoNative_X509GetSerialNumber(X509* x509); /* Shims the X509_get_issuer_name method. Returns the ASN1_INTEGER for the issuer name. */ PALEXPORT X509_NAME* CryptoNative_X509GetIssuerName(X509* x509); /* Shims the X509_get_subject_name method. Returns the X509_NAME for the subject name. */ PALEXPORT X509_NAME* CryptoNative_X509GetSubjectName(X509* x509); /* Shims the X509_check_purpose method. */ PALEXPORT int32_t CryptoNative_X509CheckPurpose(X509* x, int32_t id, int32_t ca); /* Shims the X509_issuer_name_hash method. */ PALEXPORT uint64_t CryptoNative_X509IssuerNameHash(X509* x); /* Shims the X509_get_ext_count method. */ PALEXPORT int32_t CryptoNative_X509GetExtCount(X509* x); /* Shims the X509_get_ext method. */ PALEXPORT X509_EXTENSION* CryptoNative_X509GetExt(X509* x, int32_t loc); /* Shims the X509_EXTENSION_get_object method. */ PALEXPORT ASN1_OBJECT* CryptoNative_X509ExtensionGetOid(X509_EXTENSION* x); /* Shims the X509_EXTENSION_get_data method. */ PALEXPORT ASN1_OCTET_STRING* CryptoNative_X509ExtensionGetData(X509_EXTENSION* x); /* Shims the X509_EXTENSION_get_critical method. */ PALEXPORT int32_t CryptoNative_X509ExtensionGetCritical(X509_EXTENSION* x); /* Returns the data portion of the first matched extension. */ PALEXPORT ASN1_OCTET_STRING* CryptoNative_X509FindExtensionData(X509* x, int32_t nid); /* Shims the X509_STORE_free method. */ PALEXPORT void CryptoNative_X509StoreDestory(X509_STORE* v); /* Shims the X509_STORE_add_crl method. */ PALEXPORT int32_t CryptoNative_X509StoreAddCrl(X509_STORE* ctx, X509_CRL* x); /* Sets the correct flags on the X509_STORE for the specified X509RevocationFlag. Shims the X509_STORE_set_flags method. */ PALEXPORT int32_t CryptoNative_X509StoreSetRevocationFlag(X509_STORE* ctx, X509RevocationFlag revocationFlag); /* Shims the X509_STORE_CTX_new method. */ PALEXPORT X509_STORE_CTX* CryptoNative_X509StoreCtxCreate(void); /* Shims the X509_STORE_CTX_free method. */ PALEXPORT void CryptoNative_X509StoreCtxDestroy(X509_STORE_CTX* v); /* Shims the X509_STORE_CTX_init method. */ PALEXPORT int32_t CryptoNative_X509StoreCtxInit(X509_STORE_CTX* ctx, X509_STORE* store, X509* x509, X509Stack* extraStore); /* Shims the X509_verify_cert method. */ PALEXPORT int32_t CryptoNative_X509VerifyCert(X509_STORE_CTX* ctx); /* Shims the X509_STORE_CTX_get1_chain method. */ PALEXPORT X509Stack* CryptoNative_X509StoreCtxGetChain(X509_STORE_CTX* ctx); /* Shims the X509_STORE_CTX_get_current_cert function. */ PALEXPORT X509* CryptoNative_X509StoreCtxGetCurrentCert(X509_STORE_CTX* ctx); /* Returns the interior pointer to the "untrusted" certificates collection for this X509_STORE_CTX */ PALEXPORT X509Stack* CryptoNative_X509StoreCtxGetSharedUntrusted(X509_STORE_CTX* ctx); /* Shims the X509_STORE_CTX_get_error method. */ PALEXPORT int32_t CryptoNative_X509StoreCtxGetError(X509_STORE_CTX* ctx); /* Resets ctx to before the chain was built, preserving the target cert, trust store, extra cert context, and verify parameters. */ PALEXPORT int32_t CryptoNative_X509StoreCtxReset(X509_STORE_CTX* ctx); /* Reset ctx and rebuild the chain. Returns -1 if CryptoNative_X509StoreCtxReset failed, otherwise returns the result of X509_verify_cert. */ PALEXPORT int32_t CryptoNative_X509StoreCtxRebuildChain(X509_STORE_CTX* ctx); /* Shims the X509_STORE_CTX_get_error_depth method. */ PALEXPORT int32_t CryptoNative_X509StoreCtxGetErrorDepth(X509_STORE_CTX* ctx); /* Shims the X509_STORE_CTX_set_verify_cb function. */ PALEXPORT void CryptoNative_X509StoreCtxSetVerifyCallback(X509_STORE_CTX* ctx, X509StoreVerifyCallback callback); /* Shims the X509_verify_cert_error_string method. */ PALEXPORT const char* CryptoNative_X509VerifyCertErrorString(int32_t n); /* Shims the X509_CRL_free method. */ PALEXPORT void CryptoNative_X509CrlDestroy(X509_CRL* a); /* Shims the PEM_write_bio_X509_CRL method. Returns the number of bytes written. */ PALEXPORT int32_t CryptoNative_PemWriteBioX509Crl(BIO* bio, X509_CRL* crl); /* Shims the PEM_read_bio_X509_CRL method. The new X509_CRL instance. */ PALEXPORT X509_CRL* CryptoNative_PemReadBioX509Crl(BIO* bio); /* Returns the number of bytes it will take to convert the SubjectPublicKeyInfo portion of the X509 to DER format. */ PALEXPORT int32_t CryptoNative_GetX509SubjectPublicKeyInfoDerSize(X509* x); /* Shims the i2d_X509_PUBKEY method, providing X509_get_X509_PUBKEY(x) as the input. Returns the number of bytes written to buf. */ PALEXPORT int32_t CryptoNative_EncodeX509SubjectPublicKeyInfo(X509* x, uint8_t* buf); /* Increases the reference count of the X509*, thereby increasing the number of calls required to the free function. Unlike X509Duplicate, this modifies an existing object, so no new memory is allocated. Returns the input value. */ PALEXPORT X509* CryptoNative_X509UpRef(X509* x509); /* Create a new X509_STORE, considering the certificates from systemTrust and userTrust */ PALEXPORT X509_STORE* CryptoNative_X509ChainNew(X509Stack* systemTrust, X509Stack* userTrust); /* Adds all of the simple certificates from null-or-empty-password PFX files in storePath to stack. */ PALEXPORT int32_t CryptoNative_X509StackAddDirectoryStore(X509Stack* stack, char* storePath); /* Adds all of the certificates in src to dest and increases their reference count. */ PALEXPORT int32_t CryptoNative_X509StackAddMultiple(X509Stack* dest, X509Stack* src); /* Removes any untrusted/extra certificates from the unstrusted collection that are not part of the current chain to make chain builds after Reset faster. */ PALEXPORT int32_t CryptoNative_X509StoreCtxCommitToChain(X509_STORE_CTX* storeCtx); /* Duplicates any certificate at or below the level where the error marker is. Outputs a new store with a clone of the root, if necessary. The new store does not have any properties set other than the trust. (Mainly, CRLs are lost) */ PALEXPORT int32_t CryptoNative_X509StoreCtxResetForSignatureError(X509_STORE_CTX* storeCtx, X509_STORE** newStore); /* Look for a cached OCSP response appropriate to the end-entity certificate using the issuer as determined by the chain in storeCtx. */ PALEXPORT int32_t CryptoNative_X509ChainGetCachedOcspStatus(X509_STORE_CTX* storeCtx, char* cachePath, int chainDepth); /* Build an OCSP request appropriate for the end-entity certificate using the issuer (and trust) as determined by the chain in storeCtx. */ PALEXPORT OCSP_REQUEST* CryptoNative_X509ChainBuildOcspRequest(X509_STORE_CTX* storeCtx, int chainDepth); /* Determine if the OCSP response is acceptable, and if acceptable report the status and cache the result (if appropriate) */ PALEXPORT int32_t CryptoNative_X509ChainVerifyOcsp(X509_STORE_CTX* storeCtx, OCSP_REQUEST* req, OCSP_RESPONSE* resp, char* cachePath, int chainDepth);
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "opensslshim.h" #include "pal_compiler.h" #include "pal_crypto_types.h" /* These values should be kept in sync with System.Security.Cryptography.X509Certificates.X509RevocationFlag. */ typedef enum { EndCertificateOnly = 0, EntireChain = 1, ExcludeRoot = 2, } X509RevocationFlag; /* The error codes used when verifying X509 certificate chains. These values should be kept in sync with Interop.Crypto.X509VerifyStatusCodeUniversal. Codes specific to specific versions of OpenSSL can also be returned, but are not represented in this enum due to their non-constant nature. */ typedef enum { PAL_X509_V_OK = 0, PAL_X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT = 2, PAL_X509_V_ERR_UNABLE_TO_GET_CRL = 3, PAL_X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE = 5, PAL_X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY = 6, PAL_X509_V_ERR_CERT_SIGNATURE_FAILURE = 7, PAL_X509_V_ERR_CRL_SIGNATURE_FAILURE = 8, PAL_X509_V_ERR_CERT_NOT_YET_VALID = 9, PAL_X509_V_ERR_CERT_HAS_EXPIRED = 10, PAL_X509_V_ERR_CRL_NOT_YET_VALID = 11, PAL_X509_V_ERR_CRL_HAS_EXPIRED = 12, PAL_X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD = 13, PAL_X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD = 14, PAL_X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD = 15, PAL_X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD = 16, PAL_X509_V_ERR_OUT_OF_MEM = 17, PAL_X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT = 18, PAL_X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN = 19, PAL_X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY = 20, PAL_X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE = 21, PAL_X509_V_ERR_CERT_CHAIN_TOO_LONG = 22, PAL_X509_V_ERR_CERT_REVOKED = 23, // Code 24 varies PAL_X509_V_ERR_PATH_LENGTH_EXCEEDED = 25, PAL_X509_V_ERR_INVALID_PURPOSE = 26, PAL_X509_V_ERR_CERT_UNTRUSTED = 27, PAL_X509_V_ERR_CERT_REJECTED = 28, PAL_X509_V_ERR_KEYUSAGE_NO_CERTSIGN = 32, PAL_X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER = 33, PAL_X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION = 34, PAL_X509_V_ERR_KEYUSAGE_NO_CRL_SIGN = 35, PAL_X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION = 36, PAL_X509_V_ERR_INVALID_NON_CA = 37, PAL_X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE = 39, PAL_X509_V_ERR_INVALID_EXTENSION = 41, PAL_X509_V_ERR_INVALID_POLICY_EXTENSION = 42, PAL_X509_V_ERR_NO_EXPLICIT_POLICY = 43, PAL_X509_V_ERR_DIFFERENT_CRL_SCOPE = 44, PAL_X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE = 45, PAL_X509_V_ERR_UNNESTED_RESOURCE = 46, PAL_X509_V_ERR_PERMITTED_VIOLATION = 47, PAL_X509_V_ERR_EXCLUDED_VIOLATION = 48, PAL_X509_V_ERR_SUBTREE_MINMAX = 49, PAL_X509_V_ERR_APPLICATION_VERIFICATION = 50, PAL_X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE = 51, PAL_X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX = 52, PAL_X509_V_ERR_UNSUPPORTED_NAME_SYNTAX = 53, PAL_X509_V_ERR_CRL_PATH_VALIDATION_ERROR = 54, PAL_X509_V_ERR_SUITE_B_INVALID_VERSION = 56, PAL_X509_V_ERR_SUITE_B_INVALID_ALGORITHM = 57, PAL_X509_V_ERR_SUITE_B_INVALID_CURVE = 58, PAL_X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM = 59, PAL_X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED = 60, PAL_X509_V_ERR_SUITE_B_CANNOT_SIGN_P_384_WITH_P_256 = 61, PAL_X509_V_ERR_HOSTNAME_MISMATCH = 62, PAL_X509_V_ERR_EMAIL_MISMATCH = 63, PAL_X509_V_ERR_IP_ADDRESS_MISMATCH = 64, } X509VerifyStatusCode; typedef int32_t (*X509StoreVerifyCallback)(int32_t, X509_STORE_CTX*); /* Function: GetX509EvpPublicKey Returns a EVP_PKEY* equivalent to the public key of the certificate. */ PALEXPORT EVP_PKEY* CryptoNative_GetX509EvpPublicKey(X509* x509); /* Shims the d2i_X509_CRL method and makes it easier to invoke from managed code. */ PALEXPORT X509_CRL* CryptoNative_DecodeX509Crl(const uint8_t* buf, int32_t len); /* Shims the d2i_X509 method and makes it easier to invoke from managed code. */ PALEXPORT X509* CryptoNative_DecodeX509(const uint8_t* buf, int32_t len); /* Returns the number of bytes it will take to convert the X509 to a DER format. */ PALEXPORT int32_t CryptoNative_GetX509DerSize(X509* x); /* Shims the i2d_X509 method. Returns the number of bytes written to buf. */ PALEXPORT int32_t CryptoNative_EncodeX509(X509* x, uint8_t* buf); /* Cleans up and deletes an X509 instance. Implemented by calling X509_free. No-op if a is null. The given X509 pointer is invalid after this call. Always succeeds. */ PALEXPORT void CryptoNative_X509Destroy(X509* a); /* Shims the X509_dup method. Returns the duplicated X509 instance. */ PALEXPORT X509* CryptoNative_X509Duplicate(X509* x509); /* Shims the PEM_read_bio_X509 method. Returns the read X509 instance. */ PALEXPORT X509* CryptoNative_PemReadX509FromBio(BIO* bio); /* Shims the PEM_read_bio_X509_AUX method. Returns the read X509 instance. */ PALEXPORT X509* CryptoNative_PemReadX509FromBioAux(BIO* bio); /* Shims the X509_get_serialNumber method. Returns the ASN1_INTEGER for the serial number. */ PALEXPORT ASN1_INTEGER* CryptoNative_X509GetSerialNumber(X509* x509); /* Shims the X509_get_issuer_name method. Returns the ASN1_INTEGER for the issuer name. */ PALEXPORT X509_NAME* CryptoNative_X509GetIssuerName(X509* x509); /* Shims the X509_get_subject_name method. Returns the X509_NAME for the subject name. */ PALEXPORT X509_NAME* CryptoNative_X509GetSubjectName(X509* x509); /* Shims the X509_check_purpose method. */ PALEXPORT int32_t CryptoNative_X509CheckPurpose(X509* x, int32_t id, int32_t ca); /* Shims the X509_issuer_name_hash method. */ PALEXPORT uint64_t CryptoNative_X509IssuerNameHash(X509* x); /* Shims the X509_get_ext_count method. */ PALEXPORT int32_t CryptoNative_X509GetExtCount(X509* x); /* Shims the X509_get_ext method. */ PALEXPORT X509_EXTENSION* CryptoNative_X509GetExt(X509* x, int32_t loc); /* Shims the X509_EXTENSION_get_object method. */ PALEXPORT ASN1_OBJECT* CryptoNative_X509ExtensionGetOid(X509_EXTENSION* x); /* Shims the X509_EXTENSION_get_data method. */ PALEXPORT ASN1_OCTET_STRING* CryptoNative_X509ExtensionGetData(X509_EXTENSION* x); /* Shims the X509_EXTENSION_get_critical method. */ PALEXPORT int32_t CryptoNative_X509ExtensionGetCritical(X509_EXTENSION* x); /* Returns the data portion of the first matched extension. */ PALEXPORT ASN1_OCTET_STRING* CryptoNative_X509FindExtensionData(X509* x, int32_t nid); /* Shims the X509_STORE_free method. */ PALEXPORT void CryptoNative_X509StoreDestory(X509_STORE* v); /* Shims the X509_STORE_add_crl method. */ PALEXPORT int32_t CryptoNative_X509StoreAddCrl(X509_STORE* ctx, X509_CRL* x); /* Sets the correct flags on the X509_STORE for the specified X509RevocationFlag. Shims the X509_STORE_set_flags method. */ PALEXPORT int32_t CryptoNative_X509StoreSetRevocationFlag(X509_STORE* ctx, X509RevocationFlag revocationFlag); /* Shims the X509_STORE_CTX_new method. */ PALEXPORT X509_STORE_CTX* CryptoNative_X509StoreCtxCreate(void); /* Shims the X509_STORE_CTX_free method. */ PALEXPORT void CryptoNative_X509StoreCtxDestroy(X509_STORE_CTX* v); /* Shims the X509_STORE_CTX_init method. */ PALEXPORT int32_t CryptoNative_X509StoreCtxInit(X509_STORE_CTX* ctx, X509_STORE* store, X509* x509, X509Stack* extraStore); /* Shims the X509_verify_cert method. */ PALEXPORT int32_t CryptoNative_X509VerifyCert(X509_STORE_CTX* ctx); /* Shims the X509_STORE_CTX_get1_chain method. */ PALEXPORT X509Stack* CryptoNative_X509StoreCtxGetChain(X509_STORE_CTX* ctx); /* Shims the X509_STORE_CTX_get_current_cert function. */ PALEXPORT X509* CryptoNative_X509StoreCtxGetCurrentCert(X509_STORE_CTX* ctx); /* Returns the interior pointer to the "untrusted" certificates collection for this X509_STORE_CTX */ PALEXPORT X509Stack* CryptoNative_X509StoreCtxGetSharedUntrusted(X509_STORE_CTX* ctx); /* Shims the X509_STORE_CTX_get_error method. */ PALEXPORT int32_t CryptoNative_X509StoreCtxGetError(X509_STORE_CTX* ctx); /* Resets ctx to before the chain was built, preserving the target cert, trust store, extra cert context, and verify parameters. */ PALEXPORT int32_t CryptoNative_X509StoreCtxReset(X509_STORE_CTX* ctx); /* Reset ctx and rebuild the chain. Returns -1 if CryptoNative_X509StoreCtxReset failed, otherwise returns the result of X509_verify_cert. */ PALEXPORT int32_t CryptoNative_X509StoreCtxRebuildChain(X509_STORE_CTX* ctx); /* Shims the X509_STORE_CTX_get_error_depth method. */ PALEXPORT int32_t CryptoNative_X509StoreCtxGetErrorDepth(X509_STORE_CTX* ctx); /* Shims the X509_STORE_CTX_set_verify_cb function. */ PALEXPORT void CryptoNative_X509StoreCtxSetVerifyCallback(X509_STORE_CTX* ctx, X509StoreVerifyCallback callback); /* Shims the X509_verify_cert_error_string method. */ PALEXPORT const char* CryptoNative_X509VerifyCertErrorString(int32_t n); /* Shims the X509_CRL_free method. */ PALEXPORT void CryptoNative_X509CrlDestroy(X509_CRL* a); /* Shims the PEM_write_bio_X509_CRL method. Returns the number of bytes written. */ PALEXPORT int32_t CryptoNative_PemWriteBioX509Crl(BIO* bio, X509_CRL* crl); /* Shims the PEM_read_bio_X509_CRL method. The new X509_CRL instance. */ PALEXPORT X509_CRL* CryptoNative_PemReadBioX509Crl(BIO* bio); /* Returns the number of bytes it will take to convert the SubjectPublicKeyInfo portion of the X509 to DER format. */ PALEXPORT int32_t CryptoNative_GetX509SubjectPublicKeyInfoDerSize(X509* x); /* Shims the i2d_X509_PUBKEY method, providing X509_get_X509_PUBKEY(x) as the input. Returns the number of bytes written to buf. */ PALEXPORT int32_t CryptoNative_EncodeX509SubjectPublicKeyInfo(X509* x, uint8_t* buf); /* Increases the reference count of the X509*, thereby increasing the number of calls required to the free function. Unlike X509Duplicate, this modifies an existing object, so no new memory is allocated. Returns the input value. */ PALEXPORT X509* CryptoNative_X509UpRef(X509* x509); /* Create a new X509_STORE, considering the certificates from systemTrust and userTrust */ PALEXPORT X509_STORE* CryptoNative_X509ChainNew(X509Stack* systemTrust, X509Stack* userTrust); /* Adds all of the simple certificates from null-or-empty-password PFX files in storePath to stack. */ PALEXPORT int32_t CryptoNative_X509StackAddDirectoryStore(X509Stack* stack, char* storePath); /* Adds all of the certificates in src to dest and increases their reference count. */ PALEXPORT int32_t CryptoNative_X509StackAddMultiple(X509Stack* dest, X509Stack* src); /* Removes any untrusted/extra certificates from the unstrusted collection that are not part of the current chain to make chain builds after Reset faster. */ PALEXPORT int32_t CryptoNative_X509StoreCtxCommitToChain(X509_STORE_CTX* storeCtx); /* Duplicates any certificate at or below the level where the error marker is. Outputs a new store with a clone of the root, if necessary. The new store does not have any properties set other than the trust. (Mainly, CRLs are lost) */ PALEXPORT int32_t CryptoNative_X509StoreCtxResetForSignatureError(X509_STORE_CTX* storeCtx, X509_STORE** newStore); /* Look for a cached OCSP response appropriate to the end-entity certificate using the issuer as determined by the chain in storeCtx. */ PALEXPORT int32_t CryptoNative_X509ChainGetCachedOcspStatus(X509_STORE_CTX* storeCtx, char* cachePath, int chainDepth); /* Build an OCSP request appropriate for the end-entity certificate using the issuer (and trust) as determined by the chain in storeCtx. */ PALEXPORT OCSP_REQUEST* CryptoNative_X509ChainBuildOcspRequest(X509_STORE_CTX* storeCtx, int chainDepth); /* Determine if the OCSP response is acceptable, and if acceptable report the status and cache the result (if appropriate) */ PALEXPORT int32_t CryptoNative_X509ChainVerifyOcsp(X509_STORE_CTX* storeCtx, OCSP_REQUEST* req, OCSP_RESPONSE* resp, char* cachePath, int chainDepth);
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/tests/Interop/COM/NativeClients/Events/CMakeLists.txt
project (COMClientEvents) include_directories( ${INC_PLATFORM_DIR} ) include_directories( "../../ServerContracts" ) include_directories( "../../NativeServer" ) include_directories("../") set(SOURCES EventTests.cpp App.manifest) # add the executable add_executable (COMClientEvents ${SOURCES}) target_link_libraries(COMClientEvents ${LINK_LIBRARIES_ADDITIONAL}) # Copy CoreShim manifest to project output file(GENERATE OUTPUT $<TARGET_FILE_DIR:${PROJECT_NAME}>/CoreShim.X.manifest INPUT ${CMAKE_CURRENT_SOURCE_DIR}/CoreShim.X.manifest) # add the install targets install (TARGETS COMClientEvents DESTINATION bin)
project (COMClientEvents) include_directories( ${INC_PLATFORM_DIR} ) include_directories( "../../ServerContracts" ) include_directories( "../../NativeServer" ) include_directories("../") set(SOURCES EventTests.cpp App.manifest) # add the executable add_executable (COMClientEvents ${SOURCES}) target_link_libraries(COMClientEvents ${LINK_LIBRARIES_ADDITIONAL}) # Copy CoreShim manifest to project output file(GENERATE OUTPUT $<TARGET_FILE_DIR:${PROJECT_NAME}>/CoreShim.X.manifest INPUT ${CMAKE_CURRENT_SOURCE_DIR}/CoreShim.X.manifest) # add the install targets install (TARGETS COMClientEvents DESTINATION bin)
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/native/external/zlib-intel/zlib.h
/* zlib.h -- interface of the 'zlib' general purpose compression library version 1.2.11.1, January xxth, 2017 Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Jean-loup Gailly Mark Adler [email protected] [email protected] The data format used by the zlib library is described by RFCs (Request for Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950 (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format). */ #ifndef ZLIB_H #define ZLIB_H #include "zconf.h" #ifdef __cplusplus extern "C" { #endif #define ZLIB_VERSION "1.2.11.1-motley" #define ZLIB_VERNUM 0x12b1 #define ZLIB_VER_MAJOR 1 #define ZLIB_VER_MINOR 2 #define ZLIB_VER_REVISION 11 #define ZLIB_VER_SUBREVISION 1 /* The 'zlib' compression library provides in-memory compression and decompression functions, including integrity checks of the uncompressed data. This version of the library supports only one compression method (deflation) but other algorithms will be added later and will have the same stream interface. Compression can be done in a single step if the buffers are large enough, or can be done by repeated calls of the compression function. In the latter case, the application must provide more input and/or consume the output (providing more output space) before each call. The compressed data format used by default by the in-memory functions is the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped around a deflate stream, which is itself documented in RFC 1951. The library also supports reading and writing files in gzip (.gz) format with an interface similar to that of stdio using the functions that start with "gz". The gzip format is different from the zlib format. gzip is a gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. This library can optionally read and write gzip and raw deflate streams in memory as well. The zlib format was designed to be compact and fast for use in memory and on communications channels. The gzip format was designed for single- file compression on file systems, has a larger header than zlib to maintain directory information, and uses a different, slower check method than zlib. The library does not install any signal handler. The decoder checks the consistency of the compressed data, so the library should never crash even in the case of corrupted input. */ typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); typedef void (*free_func) OF((voidpf opaque, voidpf address)); struct internal_state; typedef struct z_stream_s { z_const Bytef *next_in; /* next input byte */ uInt avail_in; /* number of bytes available at next_in */ uLong total_in; /* total number of input bytes read so far */ Bytef *next_out; /* next output byte will go here */ uInt avail_out; /* remaining free space at next_out */ uLong total_out; /* total number of bytes output so far */ z_const char *msg; /* last error message, NULL if no error */ struct internal_state FAR *state; /* not visible by applications */ alloc_func zalloc; /* used to allocate the internal state */ free_func zfree; /* used to free the internal state */ voidpf opaque; /* private data object passed to zalloc and zfree */ int data_type; /* best guess about the data type: binary or text for deflate, or the decoding state for inflate */ uLong adler; /* Adler-32 or CRC-32 value of the uncompressed data */ uLong reserved; /* reserved for future use */ } z_stream; typedef z_stream FAR *z_streamp; /* gzip header information passed to and from zlib routines. See RFC 1952 for more details on the meanings of these fields. */ typedef struct gz_header_s { int text; /* true if compressed data believed to be text */ uLong time; /* modification time */ int xflags; /* extra flags (not used when writing a gzip file) */ int os; /* operating system */ Bytef *extra; /* pointer to extra field or Z_NULL if none */ uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ uInt extra_max; /* space at extra (only when reading header) */ Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ uInt name_max; /* space at name (only when reading header) */ Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ uInt comm_max; /* space at comment (only when reading header) */ int hcrc; /* true if there was or will be a header crc */ int done; /* true when done reading gzip header (not used when writing a gzip file) */ } gz_header; typedef gz_header FAR *gz_headerp; /* The application must update next_in and avail_in when avail_in has dropped to zero. It must update next_out and avail_out when avail_out has dropped to zero. The application must initialize zalloc, zfree and opaque before calling the init function. All other fields are set by the compression library and must not be updated by the application. The opaque value provided by the application will be passed as the first parameter for calls of zalloc and zfree. This can be useful for custom memory management. The compression library attaches no meaning to the opaque value. zalloc must return Z_NULL if there is not enough memory for the object. If zlib is used in a multi-threaded application, zalloc and zfree must be thread safe. In that case, zlib is thread-safe. When zalloc and zfree are Z_NULL on entry to the initialization function, they are set to internal routines that use the standard library functions malloc() and free(). On 16-bit systems, the functions zalloc and zfree must be able to allocate exactly 65536 bytes, but will not be required to allocate more than this if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers returned by zalloc for objects of exactly 65536 bytes *must* have their offset normalized to zero. The default allocation function provided by this library ensures this (see zutil.c). To reduce memory requirements and avoid any allocation of 64K objects, at the expense of compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h). The fields total_in and total_out can be used for statistics or progress reports. After compression, total_in holds the total size of the uncompressed data and may be saved for use by the decompressor (particularly if the decompressor wants to decompress everything in a single step). */ /* constants */ #define Z_NO_FLUSH 0 #define Z_PARTIAL_FLUSH 1 #define Z_SYNC_FLUSH 2 #define Z_FULL_FLUSH 3 #define Z_FINISH 4 #define Z_BLOCK 5 #define Z_TREES 6 /* Allowed flush values; see deflate() and inflate() below for details */ #define Z_OK 0 #define Z_STREAM_END 1 #define Z_NEED_DICT 2 #define Z_ERRNO (-1) #define Z_STREAM_ERROR (-2) #define Z_DATA_ERROR (-3) #define Z_MEM_ERROR (-4) #define Z_BUF_ERROR (-5) #define Z_VERSION_ERROR (-6) /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ #define Z_NO_COMPRESSION 0 #define Z_BEST_SPEED 1 #define Z_BEST_COMPRESSION 9 #define Z_DEFAULT_COMPRESSION (-1) /* compression levels */ #define Z_FILTERED 1 #define Z_HUFFMAN_ONLY 2 #define Z_RLE 3 #define Z_FIXED 4 #define Z_DEFAULT_STRATEGY 0 /* compression strategy; see deflateInit2() below for details */ #define Z_BINARY 0 #define Z_TEXT 1 #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ #define Z_UNKNOWN 2 /* Possible values of the data_type field for deflate() */ #define Z_DEFLATED 8 /* The deflate compression method (the only one supported in this version) */ #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ #define zlib_version zlibVersion() /* for compatibility with versions < 1.0.2 */ /* basic functions */ ZEXTERN const char * ZEXPORT zlibVersion OF((void)); /* The application can compare zlibVersion and ZLIB_VERSION for consistency. If the first character differs, the library code actually used is not compatible with the zlib.h header file used by the application. This check is automatically made by deflateInit and inflateInit. */ /* ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); Initializes the internal stream state for compression. The fields zalloc, zfree and opaque must be initialized before by the caller. If zalloc and zfree are set to Z_NULL, deflateInit updates them to use default allocation functions. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: 1 gives best speed, 9 gives best compression, 0 gives no compression at all (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION requests a default compromise between speed and compression (currently equivalent to level 6). deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if level is not a valid compression level, or Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible with the version assumed by the caller (ZLIB_VERSION). msg is set to null if there is no error message. deflateInit does not perform any compression: this will be done by deflate(). */ ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); /* deflate compresses as much data as possible, and stops when the input buffer becomes empty or the output buffer becomes full. It may introduce some output latency (reading input without producing any output) except when forced to flush. The detailed semantics are as follows. deflate performs one or both of the following actions: - Compress more input starting at next_in and update next_in and avail_in accordingly. If not all input can be processed (because there is not enough room in the output buffer), next_in and avail_in are updated and processing will resume at this point for the next call of deflate(). - Generate more output starting at next_out and update next_out and avail_out accordingly. This action is forced if the parameter flush is non zero. Forcing flush frequently degrades the compression ratio, so this parameter should be set only when necessary. Some output may be provided even if flush is zero. Before the call of deflate(), the application should ensure that at least one of the actions is possible, by providing more input and/or consuming more output, and updating avail_in or avail_out accordingly; avail_out should never be zero before the call. The application can consume the compressed output when it wants, for example when the output buffer is full (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK and with zero avail_out, it must be called again after making room in the output buffer because there might be more output pending. See deflatePending(), which can be used if desired to determine whether or not there is more ouput in that case. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to decide how much data to accumulate before producing output, in order to maximize compression. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is flushed to the output buffer and the output is aligned on a byte boundary, so that the decompressor can get all input data available so far. (In particular avail_in is zero after the call if enough output space has been provided before the call.) Flushing may degrade compression for some compression algorithms and so it should be used only when necessary. This completes the current deflate block and follows it with an empty stored block that is three bits plus filler bits to the next byte, followed by four bytes (00 00 ff ff). If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the output buffer, but the output is not aligned to a byte boundary. All of the input data so far will be available to the decompressor, as for Z_SYNC_FLUSH. This completes the current deflate block and follows it with an empty fixed codes block that is 10 bits long. This assures that enough bytes are output in order for the decompressor to finish the block before the empty fixed codes block. If flush is set to Z_BLOCK, a deflate block is completed and emitted, as for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to seven bits of the current block are held to be written as the next byte after the next deflate block is completed. In this case, the decompressor may not be provided enough bits at this point in order to complete decompression of the data provided so far to the compressor. It may need to wait for the next block to be emitted. This is for advanced applications that need to control the emission of deflate blocks. If flush is set to Z_FULL_FLUSH, all output is flushed as with Z_SYNC_FLUSH, and the compression state is reset so that decompression can restart from this point if previous compressed data has been damaged or if random access is desired. Using Z_FULL_FLUSH too often can seriously degrade compression. If deflate returns with avail_out == 0, this function must be called again with the same value of the flush parameter and more output space (updated avail_out), until the flush is complete (deflate returns with non-zero avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that avail_out is greater than six to avoid repeated flush markers due to avail_out == 0 on return. If the parameter flush is set to Z_FINISH, pending input is processed, pending output is flushed and deflate returns with Z_STREAM_END if there was enough output space. If deflate returns with Z_OK or Z_BUF_ERROR, this function must be called again with Z_FINISH and more output space (updated avail_out) but no more input data, until it returns with Z_STREAM_END or an error. After deflate has returned Z_STREAM_END, the only possible operations on the stream are deflateReset or deflateEnd. Z_FINISH can be used in the first deflate call after deflateInit if all the compression is to be done in a single step. In order to complete in one call, avail_out must be at least the value returned by deflateBound (see below). Then deflate is guaranteed to return Z_STREAM_END. If not enough output space is provided, deflate will not return Z_STREAM_END, and it must be called again as described above. deflate() sets strm->adler to the Adler-32 checksum of all input read so far (that is, total_in bytes). If a gzip stream is being generated, then strm->adler will be the CRC-32 checksum of the input read so far. (See deflateInit2 below.) deflate() may update strm->data_type if it can make a good guess about the input data type (Z_BINARY or Z_TEXT). If in doubt, the data is considered binary. This field is only for information purposes and does not affect the compression algorithm in any manner. deflate() returns Z_OK if some progress has been made (more input processed or more output produced), Z_STREAM_END if all input has been consumed and all output has been produced (only when flush is set to Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example if next_in or next_out was Z_NULL or the state was inadvertently written over by the application), or Z_BUF_ERROR if no progress is possible (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not fatal, and deflate() can be called again with more input and more output space to continue compressing. */ ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); /* All dynamically allocated data structures for this stream are freed. This function discards any unprocessed input and does not flush any pending output. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state was inconsistent, Z_DATA_ERROR if the stream was freed prematurely (some input or output was discarded). In the error case, msg may be set but then points to a static string (which must not be deallocated). */ /* ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); Initializes the internal stream state for decompression. The fields next_in, avail_in, zalloc, zfree and opaque must be initialized before by the caller. In the current version of inflate, the provided input is not read or consumed. The allocation of a sliding window will be deferred to the first call of inflate (if the decompression does not complete on the first call). If zalloc and zfree are set to Z_NULL, inflateInit updates them to use default allocation functions. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_VERSION_ERROR if the zlib library version is incompatible with the version assumed by the caller, or Z_STREAM_ERROR if the parameters are invalid, such as a null pointer to the structure. msg is set to null if there is no error message. inflateInit does not perform any decompression. Actual decompression will be done by inflate(). So next_in, and avail_in, next_out, and avail_out are unused and unchanged. The current implementation of inflateInit() does not process any header information -- that is deferred until inflate() is called. */ ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); /* inflate decompresses as much data as possible, and stops when the input buffer becomes empty or the output buffer becomes full. It may introduce some output latency (reading input without producing any output) except when forced to flush. The detailed semantics are as follows. inflate performs one or both of the following actions: - Decompress more input starting at next_in and update next_in and avail_in accordingly. If not all input can be processed (because there is not enough room in the output buffer), then next_in and avail_in are updated accordingly, and processing will resume at this point for the next call of inflate(). - Generate more output starting at next_out and update next_out and avail_out accordingly. inflate() provides as much output as possible, until there is no more input data or no more space in the output buffer (see below about the flush parameter). Before the call of inflate(), the application should ensure that at least one of the actions is possible, by providing more input and/or consuming more output, and updating the next_* and avail_* values accordingly. If the caller of inflate() does not provide both available input and available output space, it is possible that there will be no progress made. The application can consume the uncompressed output when it wants, for example when the output buffer is full (avail_out == 0), or after each call of inflate(). If inflate returns Z_OK and with zero avail_out, it must be called again after making room in the output buffer because there might be more output pending. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH, Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much output as possible to the output buffer. Z_BLOCK requests that inflate() stop if and when it gets to the next deflate block boundary. When decoding the zlib or gzip format, this will cause inflate() to return immediately after the header and before the first block. When doing a raw inflate, inflate() will go ahead and process the first block, and will return when it gets to the end of that block, or when it runs out of data. The Z_BLOCK option assists in appending to or combining deflate streams. To assist in this, on return inflate() always sets strm->data_type to the number of unused bits in the last byte taken from strm->next_in, plus 64 if inflate() is currently decoding the last block in the deflate stream, plus 128 if inflate() returned immediately after decoding an end-of-block code or decoding the complete header up to just before the first byte of the deflate stream. The end-of-block will not be indicated until all of the uncompressed data from that block has been written to strm->next_out. The number of unused bits may in general be greater than seven, except when bit 7 of data_type is set, in which case the number of unused bits will be less than eight. data_type is set as noted here every time inflate() returns for all flush options, and so can be used to determine the amount of currently consumed input in bits. The Z_TREES option behaves as Z_BLOCK does, but it also returns when the end of each deflate block header is reached, before any actual data in that block is decoded. This allows the caller to determine the length of the deflate block header for later use in random access within a deflate block. 256 is added to the value of strm->data_type when inflate() returns immediately after reaching the end of the deflate block header. inflate() should normally be called until it returns Z_STREAM_END or an error. However if all decompression is to be performed in a single step (a single call of inflate), the parameter flush should be set to Z_FINISH. In this case all pending input is processed and all pending output is flushed; avail_out must be large enough to hold all of the uncompressed data for the operation to complete. (The size of the uncompressed data may have been saved by the compressor for this purpose.) The use of Z_FINISH is not required to perform an inflation in one step. However it may be used to inform inflate that a faster approach can be used for the single inflate() call. Z_FINISH also informs inflate to not maintain a sliding window if the stream completes, which reduces inflate's memory footprint. If the stream does not complete, either because not all of the stream is provided or not enough output space is provided, then a sliding window will be allocated and inflate() can be called again to continue the operation as if Z_NO_FLUSH had been used. In this implementation, inflate() always flushes as much output as possible to the output buffer, and always uses the faster approach on the first call. So the effects of the flush parameter in this implementation are on the return value of inflate() as noted below, when inflate() returns early when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of memory for a sliding window when Z_FINISH is used. If a preset dictionary is needed after this call (see inflateSetDictionary below), inflate sets strm->adler to the Adler-32 checksum of the dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise it sets strm->adler to the Adler-32 checksum of all output produced so far (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described below. At the end of the stream, inflate() checks that its computed Adler-32 checksum is equal to that saved by the compressor and returns Z_STREAM_END only if the checksum is correct. inflate() can decompress and check either zlib-wrapped or gzip-wrapped deflate data. The header type is detected automatically, if requested when initializing with inflateInit2(). Any information contained in the gzip header is not retained unless inflateGetHeader() is used. When processing gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output produced so far. The CRC-32 is checked against the gzip trailer, as is the uncompressed length, modulo 2^32. inflate() returns Z_OK if some progress has been made (more input processed or more output produced), Z_STREAM_END if the end of the compressed data has been reached and all uncompressed output has been produced, Z_NEED_DICT if a preset dictionary is needed at this point, Z_DATA_ERROR if the input data was corrupted (input stream not conforming to the zlib format or incorrect check value, in which case strm->msg points to a string with a more specific error), Z_STREAM_ERROR if the stream structure was inconsistent (for example next_in or next_out was Z_NULL, or the state was inadvertently written over by the application), Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if no progress was possible or if there was not enough room in the output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and inflate() can be called again with more input and more output space to continue decompressing. If Z_DATA_ERROR is returned, the application may then call inflateSync() to look for a good compression block if a partial recovery of the data is to be attempted. */ ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); /* All dynamically allocated data structures for this stream are freed. This function discards any unprocessed input and does not flush any pending output. inflateEnd returns Z_OK if success, or Z_STREAM_ERROR if the stream state was inconsistent. */ /* Advanced functions */ /* The following functions are needed only in some special applications. */ /* ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy)); This is another version of deflateInit with more compression options. The fields next_in, zalloc, zfree and opaque must be initialized before by the caller. The method parameter is the compression method. It must be Z_DEFLATED in this version of the library. The windowBits parameter is the base two logarithm of the window size (the size of the history buffer). It should be in the range 8..15 for this version of the library. Larger values of this parameter result in better compression at the expense of memory usage. The default value is 15 if deflateInit is used instead. For the current implementation of deflate(), a windowBits value of 8 (a window size of 256 bytes) is not supported. As a result, a request for 8 will result in 9 (a 512-byte window). In that case, providing 8 to inflateInit2() will result in an error when the zlib header with 9 is checked against the initialization of inflate(). The remedy is to not use 8 with deflateInit2() with this initialization, or at least in that case use 9 with inflateInit2(). windowBits can also be -8..-15 for raw deflate. In this case, -windowBits determines the window size. deflate() will then generate raw deflate data with no zlib header or trailer, and will not compute a check value. windowBits can also be greater than 15 for optional gzip encoding. Add 16 to windowBits to write a simple gzip header and trailer around the compressed data instead of a zlib wrapper. The gzip header will have no file name, no extra data, no comment, no modification time (set to zero), no header crc, and the operating system will be set to the appropriate value, if the operating system was determined at compile time. If a gzip stream is being written, strm->adler is a CRC-32 instead of an Adler-32. For raw deflate or gzip encoding, a request for a 256-byte window is rejected as invalid, since only the zlib header provides a means of transmitting the window size to the decompressor. The memLevel parameter specifies how much memory should be allocated for the internal compression state. memLevel=1 uses minimum memory but is slow and reduces compression ratio; memLevel=9 uses maximum memory for optimal speed. The default value is 8. See zconf.h for total memory usage as a function of windowBits and memLevel. The strategy parameter is used to tune the compression algorithm. Use the value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no string match), or Z_RLE to limit match distances to one (run-length encoding). Filtered data consists mostly of small values with a somewhat random distribution. In this case, the compression algorithm is tuned to compress them better. The effect of Z_FILTERED is to force more Huffman coding and less string matching; it is somewhat intermediate between Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy parameter only affects the compression ratio but not the correctness of the compressed output even if it is not set appropriately. Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible with the version assumed by the caller (ZLIB_VERSION). msg is set to null if there is no error message. deflateInit2 does not perform any compression: this will be done by deflate(). */ ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, const Bytef *dictionary, uInt dictLength)); /* Initializes the compression dictionary from the given byte sequence without producing any compressed output. When using the zlib format, this function must be called immediately after deflateInit, deflateInit2 or deflateReset, and before any call of deflate. When doing raw deflate, this function must be called either before any call of deflate, or immediately after the completion of a deflate block, i.e. after all input has been consumed and all output has been delivered when using any of the flush options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH. The compressor and decompressor must use exactly the same dictionary (see inflateSetDictionary). The dictionary should consist of strings (byte sequences) that are likely to be encountered later in the data to be compressed, with the most commonly used strings preferably put towards the end of the dictionary. Using a dictionary is most useful when the data to be compressed is short and can be predicted with good accuracy; the data can then be compressed better than with the default empty dictionary. Depending on the size of the compression data structures selected by deflateInit or deflateInit2, a part of the dictionary may in effect be discarded, for example if the dictionary is larger than the window size provided in deflateInit or deflateInit2. Thus the strings most likely to be useful should be put at the end of the dictionary, not at the front. In addition, the current implementation of deflate will use at most the window size minus 262 bytes of the provided dictionary. Upon return of this function, strm->adler is set to the Adler-32 value of the dictionary; the decompressor may later use this value to determine which dictionary has been used by the compressor. (The Adler-32 value applies to the whole dictionary even if only a subset of the dictionary is actually used by the compressor.) If a raw deflate was requested, then the Adler-32 value is not computed and strm->adler is not set. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is inconsistent (for example if deflate has already been called for this stream or if not at a block boundary for raw deflate). deflateSetDictionary does not perform any compression: this will be done by deflate(). */ ZEXTERN int ZEXPORT deflateGetDictionary OF((z_streamp strm, Bytef *dictionary, uInt *dictLength)); /* Returns the sliding dictionary being maintained by deflate. dictLength is set to the number of bytes in the dictionary, and that many bytes are copied to dictionary. dictionary must have enough space, where 32768 bytes is always enough. If deflateGetDictionary() is called with dictionary equal to Z_NULL, then only the dictionary length is returned, and nothing is copied. Similary, if dictLength is Z_NULL, then it is not set. deflateGetDictionary() may return a length less than the window size, even when more than the window size in input has been provided. It may return up to 258 bytes less in that case, due to how zlib's implementation of deflate manages the sliding window and lookahead for matches, where matches can be up to 258 bytes long. If the application needs the last window-size bytes of input, then that would need to be saved by the application outside of zlib. deflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the stream state is inconsistent. */ ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, z_streamp source)); /* Sets the destination stream as a complete copy of the source stream. This function can be useful when several compression strategies will be tried, for example when there are several ways of pre-processing the input data with a filter. The streams that will be discarded should then be freed by calling deflateEnd. Note that deflateCopy duplicates the internal compression state which can be quite large, so this strategy is slow and can consume lots of memory. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc being Z_NULL). msg is left unchanged in both source and destination. */ ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); /* This function is equivalent to deflateEnd followed by deflateInit, but does not free and reallocate the internal compression state. The stream will leave the compression level and any other attributes that may have been set unchanged. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc or state being Z_NULL). */ ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, int level, int strategy)); /* Dynamically update the compression level and compression strategy. The interpretation of level and strategy is as in deflateInit2(). This can be used to switch between compression and straight copy of the input data, or to switch to a different kind of input data requiring a different strategy. If the compression approach (which is a function of the level) or the strategy is changed, and if there have been any deflate() calls since the state was initialized or reset, then the input available so far is compressed with the old level and strategy using deflate(strm, Z_BLOCK). There are three approaches for the compression levels 0, 1..3, and 4..9 respectively. The new level and strategy will take effect at the next call of deflate(). If a deflate(strm, Z_BLOCK) is performed by deflateParams(), and it does not have enough output space to complete, then the parameter change will not take effect. In this case, deflateParams() can be called again with the same parameters and more output space to try again. In order to assure a change in the parameters on the first try, the deflate stream should be flushed using deflate() with Z_BLOCK or other flush request until strm.avail_out is not zero, before calling deflateParams(). Then no more input data should be provided before the deflateParams() call. If this is done, the old level and strategy will be applied to the data compressed before deflateParams(), and the new level and strategy will be applied to the the data compressed after deflateParams(). deflateParams returns Z_OK on success, Z_STREAM_ERROR if the source stream state was inconsistent or if a parameter was invalid, or Z_BUF_ERROR if there was not enough output space to complete the compression of the available input data before a change in the strategy or approach. Note that in the case of a Z_BUF_ERROR, the parameters are not changed. A return value of Z_BUF_ERROR is not fatal, in which case deflateParams() can be retried with more output space. */ ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)); /* Fine tune deflate's internal compression parameters. This should only be used by someone who understands the algorithm used by zlib's deflate for searching for the best matching string, and even then only by the most fanatic optimizer trying to squeeze out the last compressed bit for their specific input data. Read the deflate.c source code for the meaning of the max_lazy, good_length, nice_length, and max_chain parameters. deflateTune() can be called after deflateInit() or deflateInit2(), and returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. */ ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, uLong sourceLen)); /* deflateBound() returns an upper bound on the compressed size after deflation of sourceLen bytes. It must be called after deflateInit() or deflateInit2(), and after deflateSetHeader(), if used. This would be used to allocate an output buffer for deflation in a single pass, and so would be called before deflate(). If that first deflate() call is provided the sourceLen input bytes, an output buffer allocated to the size returned by deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed to return Z_STREAM_END. Note that it is possible for the compressed size to be larger than the value returned by deflateBound() if flush options other than Z_FINISH or Z_NO_FLUSH are used. */ ZEXTERN int ZEXPORT deflatePending OF((z_streamp strm, unsigned *pending, int *bits)); /* deflatePending() returns the number of bytes and bits of output that have been generated, but not yet provided in the available output. The bytes not provided would be due to the available output space having being consumed. The number of bits of output not provided are between 0 and 7, where they await more bits to join them in order to fill out a full byte. If pending or bits are Z_NULL, then those values are not set. deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent. */ ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, int bits, int value)); /* deflatePrime() inserts bits in the deflate output stream. The intent is that this function is used to start off the deflate output with the bits leftover from a previous deflate stream when appending to it. As such, this function can only be used for raw deflate, and must be used before the first deflate() call after a deflateInit2() or deflateReset(). bits must be less than or equal to 16, and that many of the least significant bits of value will be inserted in the output. deflatePrime returns Z_OK if success, Z_BUF_ERROR if there was not enough room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the source stream state was inconsistent. */ ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, gz_headerp head)); /* deflateSetHeader() provides gzip header information for when a gzip stream is requested by deflateInit2(). deflateSetHeader() may be called after deflateInit2() or deflateReset() and before the first call of deflate(). The text, time, os, extra field, name, and comment information in the provided gz_header structure are written to the gzip header (xflag is ignored -- the extra flags are set according to the compression level). The caller must assure that, if not Z_NULL, name and comment are terminated with a zero byte, and that if extra is not Z_NULL, that extra_len bytes are available there. If hcrc is true, a gzip header crc is included. Note that the current versions of the command-line version of gzip (up through version 1.3.x) do not support header crc's, and will report that it is a "multi-part gzip file" and give up. If deflateSetHeader is not used, the default gzip header has text false, the time set to zero, and os set to 255, with no extra, name, or comment fields. The gzip header is returned to the default state by deflateReset(). deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent. */ /* ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, int windowBits)); This is another version of inflateInit with an extra parameter. The fields next_in, avail_in, zalloc, zfree and opaque must be initialized before by the caller. The windowBits parameter is the base two logarithm of the maximum window size (the size of the history buffer). It should be in the range 8..15 for this version of the library. The default value is 15 if inflateInit is used instead. windowBits must be greater than or equal to the windowBits value provided to deflateInit2() while compressing, or it must be equal to 15 if deflateInit2() was not used. If a compressed stream with a larger window size is given as input, inflate() will return with the error code Z_DATA_ERROR instead of trying to allocate a larger window. windowBits can also be zero to request that inflate use the window size in the zlib header of the compressed stream. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits determines the window size. inflate() will then process raw deflate data, not looking for a zlib or gzip header, not generating a check value, and not looking for any check values for comparison at the end of the stream. This is for use with other formats that use the deflate compressed data format such as zip. Those formats provide their own check values. If a custom format is developed using the raw deflate format for compressed data, it is recommended that a check value such as an Adler-32 or a CRC-32 be applied to the uncompressed data as is done in the zlib, gzip, and zip formats. For most applications, the zlib format should be used as is. Note that comments above on the use in deflateInit2() applies to the magnitude of windowBits. windowBits can also be greater than 15 for optional gzip decoding. Add 32 to windowBits to enable zlib and gzip decoding with automatic header detection, or add 16 to decode only the gzip format (the zlib format will return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a CRC-32 instead of an Adler-32. Unlike the gunzip utility and gzread() (see below), inflate() will not automatically decode concatenated gzip streams. inflate() will return Z_STREAM_END at the end of the gzip stream. The state would need to be reset to continue decoding a subsequent gzip stream. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_VERSION_ERROR if the zlib library version is incompatible with the version assumed by the caller, or Z_STREAM_ERROR if the parameters are invalid, such as a null pointer to the structure. msg is set to null if there is no error message. inflateInit2 does not perform any decompression apart from possibly reading the zlib header if present: actual decompression will be done by inflate(). (So next_in and avail_in may be modified, but next_out and avail_out are unused and unchanged.) The current implementation of inflateInit2() does not process any header information -- that is deferred until inflate() is called. */ ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, const Bytef *dictionary, uInt dictLength)); /* Initializes the decompression dictionary from the given uncompressed byte sequence. This function must be called immediately after a call of inflate, if that call returned Z_NEED_DICT. The dictionary chosen by the compressor can be determined from the Adler-32 value returned by that call of inflate. The compressor and decompressor must use exactly the same dictionary (see deflateSetDictionary). For raw inflate, this function can be called at any time to set the dictionary. If the provided dictionary is smaller than the window and there is already data in the window, then the provided dictionary will amend what's there. The application must insure that the dictionary that was used for compression is provided. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the expected one (incorrect Adler-32 value). inflateSetDictionary does not perform any decompression: this will be done by subsequent calls of inflate(). */ ZEXTERN int ZEXPORT inflateGetDictionary OF((z_streamp strm, Bytef *dictionary, uInt *dictLength)); /* Returns the sliding dictionary being maintained by inflate. dictLength is set to the number of bytes in the dictionary, and that many bytes are copied to dictionary. dictionary must have enough space, where 32768 bytes is always enough. If inflateGetDictionary() is called with dictionary equal to Z_NULL, then only the dictionary length is returned, and nothing is copied. Similary, if dictLength is Z_NULL, then it is not set. inflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the stream state is inconsistent. */ ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); /* Skips invalid compressed data until a possible full flush point (see above for the description of deflate with Z_FULL_FLUSH) can be found, or until all available input is skipped. No output is provided. inflateSync searches for a 00 00 FF FF pattern in the compressed data. All full flush points have this pattern, but not all occurrences of this pattern are full flush points. inflateSync returns Z_OK if a possible full flush point has been found, Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point has been found, or Z_STREAM_ERROR if the stream structure was inconsistent. In the success case, the application may save the current current value of total_in which indicates where valid compressed data was found. In the error case, the application may repeatedly call inflateSync, providing more input each time, until success or end of the input data. */ ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, z_streamp source)); /* Sets the destination stream as a complete copy of the source stream. This function can be useful when randomly accessing a large stream. The first pass through the stream can periodically record the inflate state, allowing restarting inflate at those points when randomly accessing the stream. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc being Z_NULL). msg is left unchanged in both source and destination. */ ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); /* This function is equivalent to inflateEnd followed by inflateInit, but does not free and reallocate the internal decompression state. The stream will keep attributes that may have been set by inflateInit2. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc or state being Z_NULL). */ ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm, int windowBits)); /* This function is the same as inflateReset, but it also permits changing the wrap and window size requests. The windowBits parameter is interpreted the same as it is for inflateInit2. If the window size is changed, then the memory allocated for the window is freed, and the window will be reallocated by inflate() if needed. inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc or state being Z_NULL), or if the windowBits parameter is invalid. */ ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, int bits, int value)); /* This function inserts bits in the inflate input stream. The intent is that this function is used to start inflating at a bit position in the middle of a byte. The provided bits will be used before any bytes are used from next_in. This function should only be used with raw inflate, and should be used before the first inflate() call after inflateInit2() or inflateReset(). bits must be less than or equal to 16, and that many of the least significant bits of value will be inserted in the input. If bits is negative, then the input stream bit buffer is emptied. Then inflatePrime() can be called again to put bits in the buffer. This is used to clear out bits leftover after feeding inflate a block description prior to feeding inflate codes. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent. */ ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm)); /* This function returns two values, one in the lower 16 bits of the return value, and the other in the remaining upper bits, obtained by shifting the return value down 16 bits. If the upper value is -1 and the lower value is zero, then inflate() is currently decoding information outside of a block. If the upper value is -1 and the lower value is non-zero, then inflate is in the middle of a stored block, with the lower value equaling the number of bytes from the input remaining to copy. If the upper value is not -1, then it is the number of bits back from the current bit position in the input of the code (literal or length/distance pair) currently being processed. In that case the lower value is the number of bytes already emitted for that code. A code is being processed if inflate is waiting for more input to complete decoding of the code, or if it has completed decoding but is waiting for more output space to write the literal or match data. inflateMark() is used to mark locations in the input data for random access, which may be at bit positions, and to note those cases where the output of a code may span boundaries of random access blocks. The current location in the input stream can be determined from avail_in and data_type as noted in the description for the Z_BLOCK flush parameter for inflate. inflateMark returns the value noted above, or -65536 if the provided source stream state was inconsistent. */ ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, gz_headerp head)); /* inflateGetHeader() requests that gzip header information be stored in the provided gz_header structure. inflateGetHeader() may be called after inflateInit2() or inflateReset(), and before the first call of inflate(). As inflate() processes the gzip stream, head->done is zero until the header is completed, at which time head->done is set to one. If a zlib stream is being decoded, then head->done is set to -1 to indicate that there will be no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be used to force inflate() to return immediately after header processing is complete and before any actual data is decompressed. The text, time, xflags, and os fields are filled in with the gzip header contents. hcrc is set to true if there is a header CRC. (The header CRC was valid if done is set to one.) If extra is not Z_NULL, then extra_max contains the maximum number of bytes to write to extra. Once done is true, extra_len contains the actual extra field length, and extra contains the extra field, or that field truncated if extra_max is less than extra_len. If name is not Z_NULL, then up to name_max characters are written there, terminated with a zero unless the length is greater than name_max. If comment is not Z_NULL, then up to comm_max characters are written there, terminated with a zero unless the length is greater than comm_max. When any of extra, name, or comment are not Z_NULL and the respective field is not present in the header, then that field is set to Z_NULL to signal its absence. This allows the use of deflateSetHeader() with the returned structure to duplicate the header. However if those fields are set to allocated memory, then the application will need to save those pointers elsewhere so that they can be eventually freed. If inflateGetHeader is not used, then the header information is simply discarded. The header is always checked for validity, including the header CRC if present. inflateReset() will reset the process to discard the header information. The application would need to call inflateGetHeader() again to retrieve the header from the next gzip stream. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent. */ /* ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, unsigned char FAR *window)); Initialize the internal stream state for decompression using inflateBack() calls. The fields zalloc, zfree and opaque in strm must be initialized before the call. If zalloc and zfree are Z_NULL, then the default library- derived memory allocation routines are used. windowBits is the base two logarithm of the window size, in the range 8..15. window is a caller supplied buffer of that size. Except for special applications where it is assured that deflate was used with small window sizes, windowBits must be 15 and a 32K byte window must be supplied to be able to decompress general deflate streams. See inflateBack() for the usage of these routines. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of the parameters are invalid, Z_MEM_ERROR if the internal state could not be allocated, or Z_VERSION_ERROR if the version of the library does not match the version of the header file. */ typedef unsigned (*in_func) OF((void FAR *, z_const unsigned char FAR * FAR *)); typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, in_func in, void FAR *in_desc, out_func out, void FAR *out_desc)); /* inflateBack() does a raw inflate with a single call using a call-back interface for input and output. This is potentially more efficient than inflate() for file i/o applications, in that it avoids copying between the output and the sliding window by simply making the window itself the output buffer. inflate() can be faster on modern CPUs when used with large buffers. inflateBack() trusts the application to not change the output buffer passed by the output function, at least until inflateBack() returns. inflateBackInit() must be called first to allocate the internal state and to initialize the state with the user-provided window buffer. inflateBack() may then be used multiple times to inflate a complete, raw deflate stream with each call. inflateBackEnd() is then called to free the allocated state. A raw deflate stream is one with no zlib or gzip header or trailer. This routine would normally be used in a utility that reads zip or gzip files and writes out uncompressed files. The utility would decode the header and process the trailer on its own, hence this routine expects only the raw deflate stream to decompress. This is different from the default behavior of inflate(), which expects a zlib header and trailer around the deflate stream. inflateBack() uses two subroutines supplied by the caller that are then called by inflateBack() for input and output. inflateBack() calls those routines until it reads a complete deflate stream and writes out all of the uncompressed data, or until it encounters an error. The function's parameters and return types are defined above in the in_func and out_func typedefs. inflateBack() will call in(in_desc, &buf) which should return the number of bytes of provided input, and a pointer to that input in buf. If there is no input available, in() must return zero -- buf is ignored in that case -- and inflateBack() will return a buffer error. inflateBack() will call out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() should return zero on success, or non-zero on failure. If out() returns non-zero, inflateBack() will return with an error. Neither in() nor out() are permitted to change the contents of the window provided to inflateBackInit(), which is also the buffer that out() uses to write from. The length written by out() will be at most the window size. Any non-zero amount of input may be provided by in(). For convenience, inflateBack() can be provided input on the first call by setting strm->next_in and strm->avail_in. If that input is exhausted, then in() will be called. Therefore strm->next_in must be initialized before calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in must also be initialized, and then if strm->avail_in is not zero, input will initially be taken from strm->next_in[0 .. strm->avail_in - 1]. The in_desc and out_desc parameters of inflateBack() is passed as the first parameter of in() and out() respectively when they are called. These descriptors can be optionally used to pass any information that the caller- supplied in() and out() functions need to do their job. On return, inflateBack() will set strm->next_in and strm->avail_in to pass back any unused input that was provided by the last in() call. The return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR if in() or out() returned an error, Z_DATA_ERROR if there was a format error in the deflate stream (in which case strm->msg is set to indicate the nature of the error), or Z_STREAM_ERROR if the stream was not properly initialized. In the case of Z_BUF_ERROR, an input or output error can be distinguished using strm->next_in which will be Z_NULL only if in() returned an error. If strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning non-zero. (in() will always be called before out(), so strm->next_in is assured to be defined if out() returns non-zero.) Note that inflateBack() cannot return Z_OK. */ ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); /* All memory allocated by inflateBackInit() is freed. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream state was inconsistent. */ ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); /* Return flags indicating compile-time options. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: 1.0: size of uInt 3.2: size of uLong 5.4: size of voidpf (pointer) 7.6: size of z_off_t Compiler, assembler, and debug options: 8: ZLIB_DEBUG 9: ASMV or ASMINF -- use ASM code 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention 11: 0 (reserved) One-time table building (smaller code, but not thread-safe if true): 12: BUILDFIXED -- build static block decoding tables when needed 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed 14,15: 0 (reserved) Library content (indicates missing functionality): 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking deflate code when not needed) 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect and decode gzip streams (to avoid linking crc code) 18-19: 0 (reserved) Operation variations (changes in library functionality): 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate 21: FASTEST -- deflate algorithm with only one, lowest compression level 22,23: 0 (reserved) The sprintf variant used by gzprintf (zero is best): 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! 26: 0 = returns value, 1 = void -- 1 means inferred string length returned Remainder: 27-31: 0 (reserved) */ #ifndef Z_SOLO /* utility functions */ /* The following utility functions are implemented on top of the basic stream-oriented functions. To simplify the interface, some default options are assumed (compression level and memory usage, standard memory allocation functions). The source code of these utility functions can be modified if you need special options. */ ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)); /* Compresses the source buffer into the destination buffer. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be at least the value returned by compressBound(sourceLen). Upon exit, destLen is the actual size of the compressed data. compress() is equivalent to compress2() with a level parameter of Z_DEFAULT_COMPRESSION. compress returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer. */ ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen, int level)); /* Compresses the source buffer into the destination buffer. The level parameter has the same meaning as in deflateInit. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be at least the value returned by compressBound(sourceLen). Upon exit, destLen is the actual size of the compressed data. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, Z_STREAM_ERROR if the level parameter is invalid. */ ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); /* compressBound() returns an upper bound on the compressed size after compress() or compress2() on sourceLen bytes. It would be used before a compress() or compress2() call to allocate the destination buffer. */ ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)); /* Decompresses the source buffer into the destination buffer. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be large enough to hold the entire uncompressed data. (The size of the uncompressed data must have been saved previously by the compressor and transmitted to the decompressor by some mechanism outside the scope of this compression library.) Upon exit, destLen is the actual size of the uncompressed data. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. In the case where there is not enough room, uncompress() will fill the output buffer with the uncompressed data up to that point. */ ZEXTERN int ZEXPORT uncompress2 OF((Bytef *dest, uLongf *destLen, const Bytef *source, uLong *sourceLen)); /* Same as uncompress, except that sourceLen is a pointer, where the length of the source is *sourceLen. On return, *sourceLen is the number of source bytes consumed. */ /* gzip file access functions */ /* This library supports reading and writing files in gzip (.gz) format with an interface similar to that of stdio, using the functions that start with "gz". The gzip format is different from the zlib format. gzip is a gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. */ typedef struct gzFile_s *gzFile; /* semi-opaque gzip file descriptor */ /* ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); Opens a gzip (.gz) file for reading or writing. The mode parameter is as in fopen ("rb" or "wb") but can also include a compression level ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F' for fixed code compression as in "wb9F". (See the description of deflateInit2 for more information about the strategy parameter.) 'T' will request transparent writing or appending with no compression and not using the gzip format. "a" can be used instead of "w" to request that the gzip stream that will be written be appended to the file. "+" will result in an error, since reading and writing to the same gzip file is not supported. The addition of "x" when writing will create the file exclusively, which fails if the file already exists. On systems that support it, the addition of "e" when reading or writing will set the flag to close the file on an execve() call. These functions, as well as gzip, will read and decode a sequence of gzip streams in a file. The append function of gzopen() can be used to create such a file. (Also see gzflush() for another way to do this.) When appending, gzopen does not test whether the file begins with a gzip stream, nor does it look for the end of the gzip streams to begin appending. gzopen will simply append a gzip stream to the existing file. gzopen can be used to read a file which is not in gzip format; in this case gzread will directly read from the file without decompression. When reading, this will be detected automatically by looking for the magic two- byte gzip header. gzopen returns NULL if the file could not be opened, if there was insufficient memory to allocate the gzFile state, or if an invalid mode was specified (an 'r', 'w', or 'a' was not provided, or '+' was provided). errno can be checked to determine if the reason gzopen failed was that the file could not be opened. */ ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); /* gzdopen associates a gzFile with the file descriptor fd. File descriptors are obtained from calls like open, dup, creat, pipe or fileno (if the file has been previously opened with fopen). The mode parameter is as in gzopen. The next call of gzclose on the returned gzFile will also close the file descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd, mode);. The duplicated descriptor should be saved to avoid a leak, since gzdopen does not close fd if it fails. If you are using fileno() to get the file descriptor from a FILE *, then you will have to use dup() to avoid double-close()ing the file descriptor. Both gzclose() and fclose() will close the associated file descriptor, so they need to have different file descriptors. gzdopen returns NULL if there was insufficient memory to allocate the gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not provided, or '+' was provided), or if fd is -1. The file descriptor is not used until the next gz* read, write, seek, or close operation, so gzdopen will not detect if fd is invalid (unless fd is -1). */ ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size)); /* Set the internal buffer size used by this library's functions. The default buffer size is 8192 bytes. This function must be called after gzopen() or gzdopen(), and before any other calls that read or write the file. The buffer memory allocation is always deferred to the first read or write. Three times that size in buffer space is allocated. A larger buffer size of, for example, 64K or 128K bytes will noticeably increase the speed of decompression (reading). The new buffer size also affects the maximum length for gzprintf(). gzbuffer() returns 0 on success, or -1 on failure, such as being called too late. */ ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); /* Dynamically update the compression level or strategy. See the description of deflateInit2 for the meaning of these parameters. Previously provided data is flushed before the parameter change. gzsetparams returns Z_OK if success, Z_STREAM_ERROR if the file was not opened for writing, Z_ERRNO if there is an error writing the flushed data, or Z_MEM_ERROR if there is a memory allocation error. */ ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); /* Reads the given number of uncompressed bytes from the compressed file. If the input file is not in gzip format, gzread copies the given number of bytes into the buffer directly from the file. After reaching the end of a gzip stream in the input, gzread will continue to read, looking for another gzip stream. Any number of gzip streams may be concatenated in the input file, and will all be decompressed by gzread(). If something other than a gzip stream is encountered after a gzip stream, that remaining trailing garbage is ignored (and no error is returned). gzread can be used to read a gzip file that is being concurrently written. Upon reaching the end of the input, gzread will return with the available data. If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then gzclearerr can be used to clear the end of file indicator in order to permit gzread to be tried again. Z_OK indicates that a gzip stream was completed on the last gzread. Z_BUF_ERROR indicates that the input file ended in the middle of a gzip stream. Note that gzread does not return -1 in the event of an incomplete gzip stream. This error is deferred until gzclose(), which will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip stream. Alternatively, gzerror can be used before gzclose to detect this case. gzread returns the number of uncompressed bytes actually read, less than len for end of file, or -1 for error. If len is too large to fit in an int, then nothing is read, -1 is returned, and the error state is set to Z_STREAM_ERROR. */ ZEXTERN z_size_t ZEXPORT gzfread OF((voidp buf, z_size_t size, z_size_t nitems, gzFile file)); /* Read up to nitems items of size size from file to buf, otherwise operating as gzread() does. This duplicates the interface of stdio's fread(), with size_t request and return types. If the library defines size_t, then z_size_t is identical to size_t. If not, then z_size_t is an unsigned integer type that can contain a pointer. gzfread() returns the number of full items read of size size, or zero if the end of the file was reached and a full item could not be read, or if there was an error. gzerror() must be consulted if zero is returned in order to determine if there was an error. If the multiplication of size and nitems overflows, i.e. the product does not fit in a z_size_t, then nothing is read, zero is returned, and the error state is set to Z_STREAM_ERROR. In the event that the end of file is reached and only a partial item is available at the end, i.e. the remaining uncompressed data length is not a multiple of size, then the final partial item is nevetheless read into buf and the end-of-file flag is set. The length of the partial item read is not provided, but could be inferred from the result of gztell(). This behavior is the same as the behavior of fread() implementations in common libraries, but it prevents the direct use of gzfread() to read a concurrently written file, reseting and retrying on end-of-file, when size is not 1. */ ZEXTERN int ZEXPORT gzwrite OF((gzFile file, voidpc buf, unsigned len)); /* Writes the given number of uncompressed bytes into the compressed file. gzwrite returns the number of uncompressed bytes written or 0 in case of error. */ ZEXTERN z_size_t ZEXPORT gzfwrite OF((voidpc buf, z_size_t size, z_size_t nitems, gzFile file)); /* gzfwrite() writes nitems items of size size from buf to file, duplicating the interface of stdio's fwrite(), with size_t request and return types. If the library defines size_t, then z_size_t is identical to size_t. If not, then z_size_t is an unsigned integer type that can contain a pointer. gzfwrite() returns the number of full items written of size size, or zero if there was an error. If the multiplication of size and nitems overflows, i.e. the product does not fit in a z_size_t, then nothing is written, zero is returned, and the error state is set to Z_STREAM_ERROR. */ ZEXTERN int ZEXPORTVA gzprintf Z_ARG((gzFile file, const char *format, ...)); /* Converts, formats, and writes the arguments to the compressed file under control of the format string, as in fprintf. gzprintf returns the number of uncompressed bytes actually written, or a negative zlib error code in case of error. The number of uncompressed bytes written is limited to 8191, or one less than the buffer size given to gzbuffer(). The caller should assure that this limit is not exceeded. If it is exceeded, then gzprintf() will return an error (0) with nothing written. In this case, there may also be a buffer overflow with unpredictable consequences, which is possible only if zlib was compiled with the insecure functions sprintf() or vsprintf() because the secure snprintf() or vsnprintf() functions were not available. This can be determined using zlibCompileFlags(). */ ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); /* Writes the given null-terminated string to the compressed file, excluding the terminating null character. gzputs returns the number of characters written, or -1 in case of error. */ ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); /* Reads bytes from the compressed file until len-1 characters are read, or a newline character is read and transferred to buf, or an end-of-file condition is encountered. If any characters are read or if len == 1, the string is terminated with a null character. If no characters are read due to an end-of-file or len < 1, then the buffer is left untouched. gzgets returns buf which is a null-terminated string, or it returns NULL for end-of-file or in case of error. If there was an error, the contents at buf are indeterminate. */ ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); /* Writes c, converted to an unsigned char, into the compressed file. gzputc returns the value that was written, or -1 in case of error. */ ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); /* Reads one byte from the compressed file. gzgetc returns this byte or -1 in case of end of file or error. This is implemented as a macro for speed. As such, it does not do all of the checking the other functions do. I.e. it does not check to see if file is NULL, nor whether the structure file points to has been clobbered or not. */ ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); /* Push one character back onto the stream to be read as the first character on the next read. At least one character of push-back is allowed. gzungetc() returns the character pushed, or -1 on failure. gzungetc() will fail if c is -1, and may fail if a character has been pushed but not read yet. If gzungetc is used immediately after gzopen or gzdopen, at least the output buffer size of pushed characters is allowed. (See gzbuffer above.) The pushed character will be discarded if the stream is repositioned with gzseek() or gzrewind(). */ ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); /* Flushes all pending output into the compressed file. The parameter flush is as in the deflate() function. The return value is the zlib error number (see function gzerror below). gzflush is only permitted when writing. If the flush parameter is Z_FINISH, the remaining data is written and the gzip stream is completed in the output. If gzwrite() is called again, a new gzip stream will be started in the output. gzread() is able to read such concatenated gzip streams. gzflush should be called only when strictly necessary because it will degrade compression if called too often. */ /* ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, z_off_t offset, int whence)); Sets the starting position for the next gzread or gzwrite on the given compressed file. The offset represents a number of bytes in the uncompressed data stream. The whence parameter is defined as in lseek(2); the value SEEK_END is not supported. If the file is opened for reading, this function is emulated but can be extremely slow. If the file is opened for writing, only forward seeks are supported; gzseek then compresses a sequence of zeroes up to the new starting position. gzseek returns the resulting offset location as measured in bytes from the beginning of the uncompressed stream, or -1 in case of error, in particular if the file is opened for writing and the new starting position would be before the current position. */ ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); /* Rewinds the given file. This function is supported only for reading. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) */ /* ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); Returns the starting position for the next gzread or gzwrite on the given compressed file. This position represents a number of bytes in the uncompressed data stream, and is zero when starting, even if appending or reading a gzip stream from the middle of a file using gzdopen(). gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) */ /* ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file)); Returns the current offset in the file being read or written. This offset includes the count of bytes that precede the gzip stream, for example when appending or when using gzdopen() for reading. When reading, the offset does not include as yet unused buffered input. This information can be used for a progress indicator. On error, gzoffset() returns -1. */ ZEXTERN int ZEXPORT gzeof OF((gzFile file)); /* Returns true (1) if the end-of-file indicator has been set while reading, false (0) otherwise. Note that the end-of-file indicator is set only if the read tried to go past the end of the input, but came up short. Therefore, just like feof(), gzeof() may return false even if there is no more data to read, in the event that the last read request was for the exact number of bytes remaining in the input file. This will happen if the input file size is an exact multiple of the buffer size. If gzeof() returns true, then the read functions will return no more data, unless the end-of-file indicator is reset by gzclearerr() and the input file has grown since the previous end of file was detected. */ ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); /* Returns true (1) if file is being copied directly while reading, or false (0) if file is a gzip stream being decompressed. If the input file is empty, gzdirect() will return true, since the input does not contain a gzip stream. If gzdirect() is used immediately after gzopen() or gzdopen() it will cause buffers to be allocated to allow reading the file to determine if it is a gzip file. Therefore if gzbuffer() is used, it should be called before gzdirect(). When writing, gzdirect() returns true (1) if transparent writing was requested ("wT" for the gzopen() mode), or false (0) otherwise. (Note: gzdirect() is not needed when writing. Transparent writing must be explicitly requested, so the application already knows the answer. When linking statically, using gzdirect() will include all of the zlib code for gzip file reading and decompression, which may not be desired.) */ ZEXTERN int ZEXPORT gzclose OF((gzFile file)); /* Flushes all pending output if necessary, closes the compressed file and deallocates the (de)compression state. Note that once file is closed, you cannot call gzerror with file, since its structures have been deallocated. gzclose must not be called more than once on the same file, just as free must not be called more than once on the same allocation. gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the last read ended in the middle of a gzip stream, or Z_OK on success. */ ZEXTERN int ZEXPORT gzclose_r OF((gzFile file)); ZEXTERN int ZEXPORT gzclose_w OF((gzFile file)); /* Same as gzclose(), but gzclose_r() is only for use when reading, and gzclose_w() is only for use when writing or appending. The advantage to using these instead of gzclose() is that they avoid linking in zlib compression or decompression code that is not used when only reading or only writing respectively. If gzclose() is used, then both compression and decompression code will be included the application when linking to a static zlib library. */ ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); /* Returns the error message for the last error which occurred on the given compressed file. errnum is set to zlib error number. If an error occurred in the file system and not in the compression library, errnum is set to Z_ERRNO and the application may consult errno to get the exact error code. The application must not modify the returned string. Future calls to this function may invalidate the previously returned string. If file is closed, then the string previously returned by gzerror will no longer be available. gzerror() should be used to distinguish errors from end-of-file for those functions above that do not distinguish those cases in their return values. */ ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); /* Clears the error and end-of-file flags for file. This is analogous to the clearerr() function in stdio. This is useful for continuing to read a gzip file that is being written concurrently. */ #endif /* !Z_SOLO */ /* checksum functions */ /* These functions are not related to compression but are exported anyway because they might be useful in applications using the compression library. */ ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); /* Update a running Adler-32 checksum with the bytes buf[0..len-1] and return the updated checksum. If buf is Z_NULL, this function returns the required initial value for the checksum. An Adler-32 checksum is almost as reliable as a CRC-32 but can be computed much faster. Usage example: uLong adler = adler32(0L, Z_NULL, 0); while (read_buffer(buffer, length) != EOF) { adler = adler32(adler, buffer, length); } if (adler != original_adler) error(); */ ZEXTERN uLong ZEXPORT adler32_z OF((uLong adler, const Bytef *buf, z_size_t len)); /* Same as adler32(), but with a size_t length. */ /* ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, z_off_t len2)); Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. Note that the z_off_t type (like off_t) is a signed integer. If len2 is negative, the result has no meaning or utility. */ ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); /* Update a running CRC-32 with the bytes buf[0..len-1] and return the updated CRC-32. If buf is Z_NULL, this function returns the required initial value for the crc. Pre- and post-conditioning (one's complement) is performed within this function so it shouldn't be done by the application. Usage example: uLong crc = crc32(0L, Z_NULL, 0); while (read_buffer(buffer, length) != EOF) { crc = crc32(crc, buffer, length); } if (crc != original_crc) error(); */ ZEXTERN uLong ZEXPORT crc32_z OF((uLong crc, const Bytef *buf, z_size_t len)); /* Same as crc32(), but with a size_t length. */ /* ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); Combine two CRC-32 check values into one. For two sequences of bytes, seq1 and seq2 with lengths len1 and len2, CRC-32 check values were calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and len2. */ /* various hacks, don't look :) */ /* deflateInit and inflateInit are macros to allow checking the zlib version * and the compiler's view of z_stream: */ ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, const char *version, int stream_size)); ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, const char *version, int stream_size)); ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)); ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, const char *version, int stream_size)); ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, unsigned char FAR *window, const char *version, int stream_size)); #ifdef Z_PREFIX_SET # define z_deflateInit(strm, level) \ deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) # define z_inflateInit(strm) \ inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) # define z_deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) # define z_inflateInit2(strm, windowBits) \ inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ (int)sizeof(z_stream)) # define z_inflateBackInit(strm, windowBits, window) \ inflateBackInit_((strm), (windowBits), (window), \ ZLIB_VERSION, (int)sizeof(z_stream)) #else # define deflateInit(strm, level) \ deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) # define inflateInit(strm) \ inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) # define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) # define inflateInit2(strm, windowBits) \ inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ (int)sizeof(z_stream)) # define inflateBackInit(strm, windowBits, window) \ inflateBackInit_((strm), (windowBits), (window), \ ZLIB_VERSION, (int)sizeof(z_stream)) #endif #ifndef Z_SOLO /* gzgetc() macro and its supporting function and exposed data structure. Note * that the real internal state is much larger than the exposed structure. * This abbreviated structure exposes just enough for the gzgetc() macro. The * user should not mess with these exposed elements, since their names or * behavior could change in the future, perhaps even capriciously. They can * only be used by the gzgetc() macro. You have been warned. */ struct gzFile_s { unsigned have; unsigned char *next; z_off64_t pos; }; ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file)); /* backward compatibility */ #ifdef Z_PREFIX_SET # undef z_gzgetc # define z_gzgetc(g) \ ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) #else # define gzgetc(g) \ ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) #endif /* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if * both are true, the application gets the *64 functions, and the regular * functions are changed to 64 bits) -- in case these are set on systems * without large file support, _LFS64_LARGEFILE must also be true */ #ifdef Z_LARGE64 ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t)); ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t)); #endif #if !defined(ZLIB_INTERNAL) && defined(Z_WANT64) # ifdef Z_PREFIX_SET # define z_gzopen z_gzopen64 # define z_gzseek z_gzseek64 # define z_gztell z_gztell64 # define z_gzoffset z_gzoffset64 # define z_adler32_combine z_adler32_combine64 # define z_crc32_combine z_crc32_combine64 # else # define gzopen gzopen64 # define gzseek gzseek64 # define gztell gztell64 # define gzoffset gzoffset64 # define adler32_combine adler32_combine64 # define crc32_combine crc32_combine64 # endif # ifndef Z_LARGE64 ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int)); ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile)); ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile)); ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); # endif #else ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *)); ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int)); ZEXTERN z_off_t ZEXPORT gztell OF((gzFile)); ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile)); ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); #endif #else /* Z_SOLO */ ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); #endif /* !Z_SOLO */ /* undocumented functions */ ZEXTERN const char * ZEXPORT zError OF((int)); ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp)); ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table OF((void)); ZEXTERN int ZEXPORT inflateUndermine OF((z_streamp, int)); ZEXTERN int ZEXPORT inflateValidate OF((z_streamp, int)); ZEXTERN unsigned long ZEXPORT inflateCodesUsed OF ((z_streamp)); ZEXTERN int ZEXPORT inflateResetKeep OF((z_streamp)); ZEXTERN int ZEXPORT deflateResetKeep OF((z_streamp)); #if defined(_WIN32) && !defined(Z_SOLO) ZEXTERN gzFile ZEXPORT gzopen_w OF((const wchar_t *path, const char *mode)); #endif #if defined(STDC) || defined(Z_HAVE_STDARG_H) # ifndef Z_SOLO ZEXTERN int ZEXPORTVA gzvprintf Z_ARG((gzFile file, const char *format, va_list va)); # endif #endif #ifdef __cplusplus } #endif #endif /* ZLIB_H */
/* zlib.h -- interface of the 'zlib' general purpose compression library version 1.2.11.1, January xxth, 2017 Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Jean-loup Gailly Mark Adler [email protected] [email protected] The data format used by the zlib library is described by RFCs (Request for Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950 (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format). */ #ifndef ZLIB_H #define ZLIB_H #include "zconf.h" #ifdef __cplusplus extern "C" { #endif #define ZLIB_VERSION "1.2.11.1-motley" #define ZLIB_VERNUM 0x12b1 #define ZLIB_VER_MAJOR 1 #define ZLIB_VER_MINOR 2 #define ZLIB_VER_REVISION 11 #define ZLIB_VER_SUBREVISION 1 /* The 'zlib' compression library provides in-memory compression and decompression functions, including integrity checks of the uncompressed data. This version of the library supports only one compression method (deflation) but other algorithms will be added later and will have the same stream interface. Compression can be done in a single step if the buffers are large enough, or can be done by repeated calls of the compression function. In the latter case, the application must provide more input and/or consume the output (providing more output space) before each call. The compressed data format used by default by the in-memory functions is the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped around a deflate stream, which is itself documented in RFC 1951. The library also supports reading and writing files in gzip (.gz) format with an interface similar to that of stdio using the functions that start with "gz". The gzip format is different from the zlib format. gzip is a gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. This library can optionally read and write gzip and raw deflate streams in memory as well. The zlib format was designed to be compact and fast for use in memory and on communications channels. The gzip format was designed for single- file compression on file systems, has a larger header than zlib to maintain directory information, and uses a different, slower check method than zlib. The library does not install any signal handler. The decoder checks the consistency of the compressed data, so the library should never crash even in the case of corrupted input. */ typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); typedef void (*free_func) OF((voidpf opaque, voidpf address)); struct internal_state; typedef struct z_stream_s { z_const Bytef *next_in; /* next input byte */ uInt avail_in; /* number of bytes available at next_in */ uLong total_in; /* total number of input bytes read so far */ Bytef *next_out; /* next output byte will go here */ uInt avail_out; /* remaining free space at next_out */ uLong total_out; /* total number of bytes output so far */ z_const char *msg; /* last error message, NULL if no error */ struct internal_state FAR *state; /* not visible by applications */ alloc_func zalloc; /* used to allocate the internal state */ free_func zfree; /* used to free the internal state */ voidpf opaque; /* private data object passed to zalloc and zfree */ int data_type; /* best guess about the data type: binary or text for deflate, or the decoding state for inflate */ uLong adler; /* Adler-32 or CRC-32 value of the uncompressed data */ uLong reserved; /* reserved for future use */ } z_stream; typedef z_stream FAR *z_streamp; /* gzip header information passed to and from zlib routines. See RFC 1952 for more details on the meanings of these fields. */ typedef struct gz_header_s { int text; /* true if compressed data believed to be text */ uLong time; /* modification time */ int xflags; /* extra flags (not used when writing a gzip file) */ int os; /* operating system */ Bytef *extra; /* pointer to extra field or Z_NULL if none */ uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ uInt extra_max; /* space at extra (only when reading header) */ Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ uInt name_max; /* space at name (only when reading header) */ Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ uInt comm_max; /* space at comment (only when reading header) */ int hcrc; /* true if there was or will be a header crc */ int done; /* true when done reading gzip header (not used when writing a gzip file) */ } gz_header; typedef gz_header FAR *gz_headerp; /* The application must update next_in and avail_in when avail_in has dropped to zero. It must update next_out and avail_out when avail_out has dropped to zero. The application must initialize zalloc, zfree and opaque before calling the init function. All other fields are set by the compression library and must not be updated by the application. The opaque value provided by the application will be passed as the first parameter for calls of zalloc and zfree. This can be useful for custom memory management. The compression library attaches no meaning to the opaque value. zalloc must return Z_NULL if there is not enough memory for the object. If zlib is used in a multi-threaded application, zalloc and zfree must be thread safe. In that case, zlib is thread-safe. When zalloc and zfree are Z_NULL on entry to the initialization function, they are set to internal routines that use the standard library functions malloc() and free(). On 16-bit systems, the functions zalloc and zfree must be able to allocate exactly 65536 bytes, but will not be required to allocate more than this if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers returned by zalloc for objects of exactly 65536 bytes *must* have their offset normalized to zero. The default allocation function provided by this library ensures this (see zutil.c). To reduce memory requirements and avoid any allocation of 64K objects, at the expense of compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h). The fields total_in and total_out can be used for statistics or progress reports. After compression, total_in holds the total size of the uncompressed data and may be saved for use by the decompressor (particularly if the decompressor wants to decompress everything in a single step). */ /* constants */ #define Z_NO_FLUSH 0 #define Z_PARTIAL_FLUSH 1 #define Z_SYNC_FLUSH 2 #define Z_FULL_FLUSH 3 #define Z_FINISH 4 #define Z_BLOCK 5 #define Z_TREES 6 /* Allowed flush values; see deflate() and inflate() below for details */ #define Z_OK 0 #define Z_STREAM_END 1 #define Z_NEED_DICT 2 #define Z_ERRNO (-1) #define Z_STREAM_ERROR (-2) #define Z_DATA_ERROR (-3) #define Z_MEM_ERROR (-4) #define Z_BUF_ERROR (-5) #define Z_VERSION_ERROR (-6) /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ #define Z_NO_COMPRESSION 0 #define Z_BEST_SPEED 1 #define Z_BEST_COMPRESSION 9 #define Z_DEFAULT_COMPRESSION (-1) /* compression levels */ #define Z_FILTERED 1 #define Z_HUFFMAN_ONLY 2 #define Z_RLE 3 #define Z_FIXED 4 #define Z_DEFAULT_STRATEGY 0 /* compression strategy; see deflateInit2() below for details */ #define Z_BINARY 0 #define Z_TEXT 1 #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ #define Z_UNKNOWN 2 /* Possible values of the data_type field for deflate() */ #define Z_DEFLATED 8 /* The deflate compression method (the only one supported in this version) */ #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ #define zlib_version zlibVersion() /* for compatibility with versions < 1.0.2 */ /* basic functions */ ZEXTERN const char * ZEXPORT zlibVersion OF((void)); /* The application can compare zlibVersion and ZLIB_VERSION for consistency. If the first character differs, the library code actually used is not compatible with the zlib.h header file used by the application. This check is automatically made by deflateInit and inflateInit. */ /* ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); Initializes the internal stream state for compression. The fields zalloc, zfree and opaque must be initialized before by the caller. If zalloc and zfree are set to Z_NULL, deflateInit updates them to use default allocation functions. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: 1 gives best speed, 9 gives best compression, 0 gives no compression at all (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION requests a default compromise between speed and compression (currently equivalent to level 6). deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if level is not a valid compression level, or Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible with the version assumed by the caller (ZLIB_VERSION). msg is set to null if there is no error message. deflateInit does not perform any compression: this will be done by deflate(). */ ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); /* deflate compresses as much data as possible, and stops when the input buffer becomes empty or the output buffer becomes full. It may introduce some output latency (reading input without producing any output) except when forced to flush. The detailed semantics are as follows. deflate performs one or both of the following actions: - Compress more input starting at next_in and update next_in and avail_in accordingly. If not all input can be processed (because there is not enough room in the output buffer), next_in and avail_in are updated and processing will resume at this point for the next call of deflate(). - Generate more output starting at next_out and update next_out and avail_out accordingly. This action is forced if the parameter flush is non zero. Forcing flush frequently degrades the compression ratio, so this parameter should be set only when necessary. Some output may be provided even if flush is zero. Before the call of deflate(), the application should ensure that at least one of the actions is possible, by providing more input and/or consuming more output, and updating avail_in or avail_out accordingly; avail_out should never be zero before the call. The application can consume the compressed output when it wants, for example when the output buffer is full (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK and with zero avail_out, it must be called again after making room in the output buffer because there might be more output pending. See deflatePending(), which can be used if desired to determine whether or not there is more ouput in that case. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to decide how much data to accumulate before producing output, in order to maximize compression. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is flushed to the output buffer and the output is aligned on a byte boundary, so that the decompressor can get all input data available so far. (In particular avail_in is zero after the call if enough output space has been provided before the call.) Flushing may degrade compression for some compression algorithms and so it should be used only when necessary. This completes the current deflate block and follows it with an empty stored block that is three bits plus filler bits to the next byte, followed by four bytes (00 00 ff ff). If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the output buffer, but the output is not aligned to a byte boundary. All of the input data so far will be available to the decompressor, as for Z_SYNC_FLUSH. This completes the current deflate block and follows it with an empty fixed codes block that is 10 bits long. This assures that enough bytes are output in order for the decompressor to finish the block before the empty fixed codes block. If flush is set to Z_BLOCK, a deflate block is completed and emitted, as for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to seven bits of the current block are held to be written as the next byte after the next deflate block is completed. In this case, the decompressor may not be provided enough bits at this point in order to complete decompression of the data provided so far to the compressor. It may need to wait for the next block to be emitted. This is for advanced applications that need to control the emission of deflate blocks. If flush is set to Z_FULL_FLUSH, all output is flushed as with Z_SYNC_FLUSH, and the compression state is reset so that decompression can restart from this point if previous compressed data has been damaged or if random access is desired. Using Z_FULL_FLUSH too often can seriously degrade compression. If deflate returns with avail_out == 0, this function must be called again with the same value of the flush parameter and more output space (updated avail_out), until the flush is complete (deflate returns with non-zero avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that avail_out is greater than six to avoid repeated flush markers due to avail_out == 0 on return. If the parameter flush is set to Z_FINISH, pending input is processed, pending output is flushed and deflate returns with Z_STREAM_END if there was enough output space. If deflate returns with Z_OK or Z_BUF_ERROR, this function must be called again with Z_FINISH and more output space (updated avail_out) but no more input data, until it returns with Z_STREAM_END or an error. After deflate has returned Z_STREAM_END, the only possible operations on the stream are deflateReset or deflateEnd. Z_FINISH can be used in the first deflate call after deflateInit if all the compression is to be done in a single step. In order to complete in one call, avail_out must be at least the value returned by deflateBound (see below). Then deflate is guaranteed to return Z_STREAM_END. If not enough output space is provided, deflate will not return Z_STREAM_END, and it must be called again as described above. deflate() sets strm->adler to the Adler-32 checksum of all input read so far (that is, total_in bytes). If a gzip stream is being generated, then strm->adler will be the CRC-32 checksum of the input read so far. (See deflateInit2 below.) deflate() may update strm->data_type if it can make a good guess about the input data type (Z_BINARY or Z_TEXT). If in doubt, the data is considered binary. This field is only for information purposes and does not affect the compression algorithm in any manner. deflate() returns Z_OK if some progress has been made (more input processed or more output produced), Z_STREAM_END if all input has been consumed and all output has been produced (only when flush is set to Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example if next_in or next_out was Z_NULL or the state was inadvertently written over by the application), or Z_BUF_ERROR if no progress is possible (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not fatal, and deflate() can be called again with more input and more output space to continue compressing. */ ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); /* All dynamically allocated data structures for this stream are freed. This function discards any unprocessed input and does not flush any pending output. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state was inconsistent, Z_DATA_ERROR if the stream was freed prematurely (some input or output was discarded). In the error case, msg may be set but then points to a static string (which must not be deallocated). */ /* ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); Initializes the internal stream state for decompression. The fields next_in, avail_in, zalloc, zfree and opaque must be initialized before by the caller. In the current version of inflate, the provided input is not read or consumed. The allocation of a sliding window will be deferred to the first call of inflate (if the decompression does not complete on the first call). If zalloc and zfree are set to Z_NULL, inflateInit updates them to use default allocation functions. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_VERSION_ERROR if the zlib library version is incompatible with the version assumed by the caller, or Z_STREAM_ERROR if the parameters are invalid, such as a null pointer to the structure. msg is set to null if there is no error message. inflateInit does not perform any decompression. Actual decompression will be done by inflate(). So next_in, and avail_in, next_out, and avail_out are unused and unchanged. The current implementation of inflateInit() does not process any header information -- that is deferred until inflate() is called. */ ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); /* inflate decompresses as much data as possible, and stops when the input buffer becomes empty or the output buffer becomes full. It may introduce some output latency (reading input without producing any output) except when forced to flush. The detailed semantics are as follows. inflate performs one or both of the following actions: - Decompress more input starting at next_in and update next_in and avail_in accordingly. If not all input can be processed (because there is not enough room in the output buffer), then next_in and avail_in are updated accordingly, and processing will resume at this point for the next call of inflate(). - Generate more output starting at next_out and update next_out and avail_out accordingly. inflate() provides as much output as possible, until there is no more input data or no more space in the output buffer (see below about the flush parameter). Before the call of inflate(), the application should ensure that at least one of the actions is possible, by providing more input and/or consuming more output, and updating the next_* and avail_* values accordingly. If the caller of inflate() does not provide both available input and available output space, it is possible that there will be no progress made. The application can consume the uncompressed output when it wants, for example when the output buffer is full (avail_out == 0), or after each call of inflate(). If inflate returns Z_OK and with zero avail_out, it must be called again after making room in the output buffer because there might be more output pending. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH, Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much output as possible to the output buffer. Z_BLOCK requests that inflate() stop if and when it gets to the next deflate block boundary. When decoding the zlib or gzip format, this will cause inflate() to return immediately after the header and before the first block. When doing a raw inflate, inflate() will go ahead and process the first block, and will return when it gets to the end of that block, or when it runs out of data. The Z_BLOCK option assists in appending to or combining deflate streams. To assist in this, on return inflate() always sets strm->data_type to the number of unused bits in the last byte taken from strm->next_in, plus 64 if inflate() is currently decoding the last block in the deflate stream, plus 128 if inflate() returned immediately after decoding an end-of-block code or decoding the complete header up to just before the first byte of the deflate stream. The end-of-block will not be indicated until all of the uncompressed data from that block has been written to strm->next_out. The number of unused bits may in general be greater than seven, except when bit 7 of data_type is set, in which case the number of unused bits will be less than eight. data_type is set as noted here every time inflate() returns for all flush options, and so can be used to determine the amount of currently consumed input in bits. The Z_TREES option behaves as Z_BLOCK does, but it also returns when the end of each deflate block header is reached, before any actual data in that block is decoded. This allows the caller to determine the length of the deflate block header for later use in random access within a deflate block. 256 is added to the value of strm->data_type when inflate() returns immediately after reaching the end of the deflate block header. inflate() should normally be called until it returns Z_STREAM_END or an error. However if all decompression is to be performed in a single step (a single call of inflate), the parameter flush should be set to Z_FINISH. In this case all pending input is processed and all pending output is flushed; avail_out must be large enough to hold all of the uncompressed data for the operation to complete. (The size of the uncompressed data may have been saved by the compressor for this purpose.) The use of Z_FINISH is not required to perform an inflation in one step. However it may be used to inform inflate that a faster approach can be used for the single inflate() call. Z_FINISH also informs inflate to not maintain a sliding window if the stream completes, which reduces inflate's memory footprint. If the stream does not complete, either because not all of the stream is provided or not enough output space is provided, then a sliding window will be allocated and inflate() can be called again to continue the operation as if Z_NO_FLUSH had been used. In this implementation, inflate() always flushes as much output as possible to the output buffer, and always uses the faster approach on the first call. So the effects of the flush parameter in this implementation are on the return value of inflate() as noted below, when inflate() returns early when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of memory for a sliding window when Z_FINISH is used. If a preset dictionary is needed after this call (see inflateSetDictionary below), inflate sets strm->adler to the Adler-32 checksum of the dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise it sets strm->adler to the Adler-32 checksum of all output produced so far (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described below. At the end of the stream, inflate() checks that its computed Adler-32 checksum is equal to that saved by the compressor and returns Z_STREAM_END only if the checksum is correct. inflate() can decompress and check either zlib-wrapped or gzip-wrapped deflate data. The header type is detected automatically, if requested when initializing with inflateInit2(). Any information contained in the gzip header is not retained unless inflateGetHeader() is used. When processing gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output produced so far. The CRC-32 is checked against the gzip trailer, as is the uncompressed length, modulo 2^32. inflate() returns Z_OK if some progress has been made (more input processed or more output produced), Z_STREAM_END if the end of the compressed data has been reached and all uncompressed output has been produced, Z_NEED_DICT if a preset dictionary is needed at this point, Z_DATA_ERROR if the input data was corrupted (input stream not conforming to the zlib format or incorrect check value, in which case strm->msg points to a string with a more specific error), Z_STREAM_ERROR if the stream structure was inconsistent (for example next_in or next_out was Z_NULL, or the state was inadvertently written over by the application), Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if no progress was possible or if there was not enough room in the output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and inflate() can be called again with more input and more output space to continue decompressing. If Z_DATA_ERROR is returned, the application may then call inflateSync() to look for a good compression block if a partial recovery of the data is to be attempted. */ ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); /* All dynamically allocated data structures for this stream are freed. This function discards any unprocessed input and does not flush any pending output. inflateEnd returns Z_OK if success, or Z_STREAM_ERROR if the stream state was inconsistent. */ /* Advanced functions */ /* The following functions are needed only in some special applications. */ /* ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy)); This is another version of deflateInit with more compression options. The fields next_in, zalloc, zfree and opaque must be initialized before by the caller. The method parameter is the compression method. It must be Z_DEFLATED in this version of the library. The windowBits parameter is the base two logarithm of the window size (the size of the history buffer). It should be in the range 8..15 for this version of the library. Larger values of this parameter result in better compression at the expense of memory usage. The default value is 15 if deflateInit is used instead. For the current implementation of deflate(), a windowBits value of 8 (a window size of 256 bytes) is not supported. As a result, a request for 8 will result in 9 (a 512-byte window). In that case, providing 8 to inflateInit2() will result in an error when the zlib header with 9 is checked against the initialization of inflate(). The remedy is to not use 8 with deflateInit2() with this initialization, or at least in that case use 9 with inflateInit2(). windowBits can also be -8..-15 for raw deflate. In this case, -windowBits determines the window size. deflate() will then generate raw deflate data with no zlib header or trailer, and will not compute a check value. windowBits can also be greater than 15 for optional gzip encoding. Add 16 to windowBits to write a simple gzip header and trailer around the compressed data instead of a zlib wrapper. The gzip header will have no file name, no extra data, no comment, no modification time (set to zero), no header crc, and the operating system will be set to the appropriate value, if the operating system was determined at compile time. If a gzip stream is being written, strm->adler is a CRC-32 instead of an Adler-32. For raw deflate or gzip encoding, a request for a 256-byte window is rejected as invalid, since only the zlib header provides a means of transmitting the window size to the decompressor. The memLevel parameter specifies how much memory should be allocated for the internal compression state. memLevel=1 uses minimum memory but is slow and reduces compression ratio; memLevel=9 uses maximum memory for optimal speed. The default value is 8. See zconf.h for total memory usage as a function of windowBits and memLevel. The strategy parameter is used to tune the compression algorithm. Use the value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no string match), or Z_RLE to limit match distances to one (run-length encoding). Filtered data consists mostly of small values with a somewhat random distribution. In this case, the compression algorithm is tuned to compress them better. The effect of Z_FILTERED is to force more Huffman coding and less string matching; it is somewhat intermediate between Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy parameter only affects the compression ratio but not the correctness of the compressed output even if it is not set appropriately. Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible with the version assumed by the caller (ZLIB_VERSION). msg is set to null if there is no error message. deflateInit2 does not perform any compression: this will be done by deflate(). */ ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, const Bytef *dictionary, uInt dictLength)); /* Initializes the compression dictionary from the given byte sequence without producing any compressed output. When using the zlib format, this function must be called immediately after deflateInit, deflateInit2 or deflateReset, and before any call of deflate. When doing raw deflate, this function must be called either before any call of deflate, or immediately after the completion of a deflate block, i.e. after all input has been consumed and all output has been delivered when using any of the flush options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH. The compressor and decompressor must use exactly the same dictionary (see inflateSetDictionary). The dictionary should consist of strings (byte sequences) that are likely to be encountered later in the data to be compressed, with the most commonly used strings preferably put towards the end of the dictionary. Using a dictionary is most useful when the data to be compressed is short and can be predicted with good accuracy; the data can then be compressed better than with the default empty dictionary. Depending on the size of the compression data structures selected by deflateInit or deflateInit2, a part of the dictionary may in effect be discarded, for example if the dictionary is larger than the window size provided in deflateInit or deflateInit2. Thus the strings most likely to be useful should be put at the end of the dictionary, not at the front. In addition, the current implementation of deflate will use at most the window size minus 262 bytes of the provided dictionary. Upon return of this function, strm->adler is set to the Adler-32 value of the dictionary; the decompressor may later use this value to determine which dictionary has been used by the compressor. (The Adler-32 value applies to the whole dictionary even if only a subset of the dictionary is actually used by the compressor.) If a raw deflate was requested, then the Adler-32 value is not computed and strm->adler is not set. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is inconsistent (for example if deflate has already been called for this stream or if not at a block boundary for raw deflate). deflateSetDictionary does not perform any compression: this will be done by deflate(). */ ZEXTERN int ZEXPORT deflateGetDictionary OF((z_streamp strm, Bytef *dictionary, uInt *dictLength)); /* Returns the sliding dictionary being maintained by deflate. dictLength is set to the number of bytes in the dictionary, and that many bytes are copied to dictionary. dictionary must have enough space, where 32768 bytes is always enough. If deflateGetDictionary() is called with dictionary equal to Z_NULL, then only the dictionary length is returned, and nothing is copied. Similary, if dictLength is Z_NULL, then it is not set. deflateGetDictionary() may return a length less than the window size, even when more than the window size in input has been provided. It may return up to 258 bytes less in that case, due to how zlib's implementation of deflate manages the sliding window and lookahead for matches, where matches can be up to 258 bytes long. If the application needs the last window-size bytes of input, then that would need to be saved by the application outside of zlib. deflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the stream state is inconsistent. */ ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, z_streamp source)); /* Sets the destination stream as a complete copy of the source stream. This function can be useful when several compression strategies will be tried, for example when there are several ways of pre-processing the input data with a filter. The streams that will be discarded should then be freed by calling deflateEnd. Note that deflateCopy duplicates the internal compression state which can be quite large, so this strategy is slow and can consume lots of memory. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc being Z_NULL). msg is left unchanged in both source and destination. */ ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); /* This function is equivalent to deflateEnd followed by deflateInit, but does not free and reallocate the internal compression state. The stream will leave the compression level and any other attributes that may have been set unchanged. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc or state being Z_NULL). */ ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, int level, int strategy)); /* Dynamically update the compression level and compression strategy. The interpretation of level and strategy is as in deflateInit2(). This can be used to switch between compression and straight copy of the input data, or to switch to a different kind of input data requiring a different strategy. If the compression approach (which is a function of the level) or the strategy is changed, and if there have been any deflate() calls since the state was initialized or reset, then the input available so far is compressed with the old level and strategy using deflate(strm, Z_BLOCK). There are three approaches for the compression levels 0, 1..3, and 4..9 respectively. The new level and strategy will take effect at the next call of deflate(). If a deflate(strm, Z_BLOCK) is performed by deflateParams(), and it does not have enough output space to complete, then the parameter change will not take effect. In this case, deflateParams() can be called again with the same parameters and more output space to try again. In order to assure a change in the parameters on the first try, the deflate stream should be flushed using deflate() with Z_BLOCK or other flush request until strm.avail_out is not zero, before calling deflateParams(). Then no more input data should be provided before the deflateParams() call. If this is done, the old level and strategy will be applied to the data compressed before deflateParams(), and the new level and strategy will be applied to the the data compressed after deflateParams(). deflateParams returns Z_OK on success, Z_STREAM_ERROR if the source stream state was inconsistent or if a parameter was invalid, or Z_BUF_ERROR if there was not enough output space to complete the compression of the available input data before a change in the strategy or approach. Note that in the case of a Z_BUF_ERROR, the parameters are not changed. A return value of Z_BUF_ERROR is not fatal, in which case deflateParams() can be retried with more output space. */ ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)); /* Fine tune deflate's internal compression parameters. This should only be used by someone who understands the algorithm used by zlib's deflate for searching for the best matching string, and even then only by the most fanatic optimizer trying to squeeze out the last compressed bit for their specific input data. Read the deflate.c source code for the meaning of the max_lazy, good_length, nice_length, and max_chain parameters. deflateTune() can be called after deflateInit() or deflateInit2(), and returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. */ ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, uLong sourceLen)); /* deflateBound() returns an upper bound on the compressed size after deflation of sourceLen bytes. It must be called after deflateInit() or deflateInit2(), and after deflateSetHeader(), if used. This would be used to allocate an output buffer for deflation in a single pass, and so would be called before deflate(). If that first deflate() call is provided the sourceLen input bytes, an output buffer allocated to the size returned by deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed to return Z_STREAM_END. Note that it is possible for the compressed size to be larger than the value returned by deflateBound() if flush options other than Z_FINISH or Z_NO_FLUSH are used. */ ZEXTERN int ZEXPORT deflatePending OF((z_streamp strm, unsigned *pending, int *bits)); /* deflatePending() returns the number of bytes and bits of output that have been generated, but not yet provided in the available output. The bytes not provided would be due to the available output space having being consumed. The number of bits of output not provided are between 0 and 7, where they await more bits to join them in order to fill out a full byte. If pending or bits are Z_NULL, then those values are not set. deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent. */ ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, int bits, int value)); /* deflatePrime() inserts bits in the deflate output stream. The intent is that this function is used to start off the deflate output with the bits leftover from a previous deflate stream when appending to it. As such, this function can only be used for raw deflate, and must be used before the first deflate() call after a deflateInit2() or deflateReset(). bits must be less than or equal to 16, and that many of the least significant bits of value will be inserted in the output. deflatePrime returns Z_OK if success, Z_BUF_ERROR if there was not enough room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the source stream state was inconsistent. */ ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, gz_headerp head)); /* deflateSetHeader() provides gzip header information for when a gzip stream is requested by deflateInit2(). deflateSetHeader() may be called after deflateInit2() or deflateReset() and before the first call of deflate(). The text, time, os, extra field, name, and comment information in the provided gz_header structure are written to the gzip header (xflag is ignored -- the extra flags are set according to the compression level). The caller must assure that, if not Z_NULL, name and comment are terminated with a zero byte, and that if extra is not Z_NULL, that extra_len bytes are available there. If hcrc is true, a gzip header crc is included. Note that the current versions of the command-line version of gzip (up through version 1.3.x) do not support header crc's, and will report that it is a "multi-part gzip file" and give up. If deflateSetHeader is not used, the default gzip header has text false, the time set to zero, and os set to 255, with no extra, name, or comment fields. The gzip header is returned to the default state by deflateReset(). deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent. */ /* ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, int windowBits)); This is another version of inflateInit with an extra parameter. The fields next_in, avail_in, zalloc, zfree and opaque must be initialized before by the caller. The windowBits parameter is the base two logarithm of the maximum window size (the size of the history buffer). It should be in the range 8..15 for this version of the library. The default value is 15 if inflateInit is used instead. windowBits must be greater than or equal to the windowBits value provided to deflateInit2() while compressing, or it must be equal to 15 if deflateInit2() was not used. If a compressed stream with a larger window size is given as input, inflate() will return with the error code Z_DATA_ERROR instead of trying to allocate a larger window. windowBits can also be zero to request that inflate use the window size in the zlib header of the compressed stream. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits determines the window size. inflate() will then process raw deflate data, not looking for a zlib or gzip header, not generating a check value, and not looking for any check values for comparison at the end of the stream. This is for use with other formats that use the deflate compressed data format such as zip. Those formats provide their own check values. If a custom format is developed using the raw deflate format for compressed data, it is recommended that a check value such as an Adler-32 or a CRC-32 be applied to the uncompressed data as is done in the zlib, gzip, and zip formats. For most applications, the zlib format should be used as is. Note that comments above on the use in deflateInit2() applies to the magnitude of windowBits. windowBits can also be greater than 15 for optional gzip decoding. Add 32 to windowBits to enable zlib and gzip decoding with automatic header detection, or add 16 to decode only the gzip format (the zlib format will return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a CRC-32 instead of an Adler-32. Unlike the gunzip utility and gzread() (see below), inflate() will not automatically decode concatenated gzip streams. inflate() will return Z_STREAM_END at the end of the gzip stream. The state would need to be reset to continue decoding a subsequent gzip stream. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_VERSION_ERROR if the zlib library version is incompatible with the version assumed by the caller, or Z_STREAM_ERROR if the parameters are invalid, such as a null pointer to the structure. msg is set to null if there is no error message. inflateInit2 does not perform any decompression apart from possibly reading the zlib header if present: actual decompression will be done by inflate(). (So next_in and avail_in may be modified, but next_out and avail_out are unused and unchanged.) The current implementation of inflateInit2() does not process any header information -- that is deferred until inflate() is called. */ ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, const Bytef *dictionary, uInt dictLength)); /* Initializes the decompression dictionary from the given uncompressed byte sequence. This function must be called immediately after a call of inflate, if that call returned Z_NEED_DICT. The dictionary chosen by the compressor can be determined from the Adler-32 value returned by that call of inflate. The compressor and decompressor must use exactly the same dictionary (see deflateSetDictionary). For raw inflate, this function can be called at any time to set the dictionary. If the provided dictionary is smaller than the window and there is already data in the window, then the provided dictionary will amend what's there. The application must insure that the dictionary that was used for compression is provided. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the expected one (incorrect Adler-32 value). inflateSetDictionary does not perform any decompression: this will be done by subsequent calls of inflate(). */ ZEXTERN int ZEXPORT inflateGetDictionary OF((z_streamp strm, Bytef *dictionary, uInt *dictLength)); /* Returns the sliding dictionary being maintained by inflate. dictLength is set to the number of bytes in the dictionary, and that many bytes are copied to dictionary. dictionary must have enough space, where 32768 bytes is always enough. If inflateGetDictionary() is called with dictionary equal to Z_NULL, then only the dictionary length is returned, and nothing is copied. Similary, if dictLength is Z_NULL, then it is not set. inflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the stream state is inconsistent. */ ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); /* Skips invalid compressed data until a possible full flush point (see above for the description of deflate with Z_FULL_FLUSH) can be found, or until all available input is skipped. No output is provided. inflateSync searches for a 00 00 FF FF pattern in the compressed data. All full flush points have this pattern, but not all occurrences of this pattern are full flush points. inflateSync returns Z_OK if a possible full flush point has been found, Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point has been found, or Z_STREAM_ERROR if the stream structure was inconsistent. In the success case, the application may save the current current value of total_in which indicates where valid compressed data was found. In the error case, the application may repeatedly call inflateSync, providing more input each time, until success or end of the input data. */ ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, z_streamp source)); /* Sets the destination stream as a complete copy of the source stream. This function can be useful when randomly accessing a large stream. The first pass through the stream can periodically record the inflate state, allowing restarting inflate at those points when randomly accessing the stream. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc being Z_NULL). msg is left unchanged in both source and destination. */ ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); /* This function is equivalent to inflateEnd followed by inflateInit, but does not free and reallocate the internal decompression state. The stream will keep attributes that may have been set by inflateInit2. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc or state being Z_NULL). */ ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm, int windowBits)); /* This function is the same as inflateReset, but it also permits changing the wrap and window size requests. The windowBits parameter is interpreted the same as it is for inflateInit2. If the window size is changed, then the memory allocated for the window is freed, and the window will be reallocated by inflate() if needed. inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc or state being Z_NULL), or if the windowBits parameter is invalid. */ ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, int bits, int value)); /* This function inserts bits in the inflate input stream. The intent is that this function is used to start inflating at a bit position in the middle of a byte. The provided bits will be used before any bytes are used from next_in. This function should only be used with raw inflate, and should be used before the first inflate() call after inflateInit2() or inflateReset(). bits must be less than or equal to 16, and that many of the least significant bits of value will be inserted in the input. If bits is negative, then the input stream bit buffer is emptied. Then inflatePrime() can be called again to put bits in the buffer. This is used to clear out bits leftover after feeding inflate a block description prior to feeding inflate codes. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent. */ ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm)); /* This function returns two values, one in the lower 16 bits of the return value, and the other in the remaining upper bits, obtained by shifting the return value down 16 bits. If the upper value is -1 and the lower value is zero, then inflate() is currently decoding information outside of a block. If the upper value is -1 and the lower value is non-zero, then inflate is in the middle of a stored block, with the lower value equaling the number of bytes from the input remaining to copy. If the upper value is not -1, then it is the number of bits back from the current bit position in the input of the code (literal or length/distance pair) currently being processed. In that case the lower value is the number of bytes already emitted for that code. A code is being processed if inflate is waiting for more input to complete decoding of the code, or if it has completed decoding but is waiting for more output space to write the literal or match data. inflateMark() is used to mark locations in the input data for random access, which may be at bit positions, and to note those cases where the output of a code may span boundaries of random access blocks. The current location in the input stream can be determined from avail_in and data_type as noted in the description for the Z_BLOCK flush parameter for inflate. inflateMark returns the value noted above, or -65536 if the provided source stream state was inconsistent. */ ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, gz_headerp head)); /* inflateGetHeader() requests that gzip header information be stored in the provided gz_header structure. inflateGetHeader() may be called after inflateInit2() or inflateReset(), and before the first call of inflate(). As inflate() processes the gzip stream, head->done is zero until the header is completed, at which time head->done is set to one. If a zlib stream is being decoded, then head->done is set to -1 to indicate that there will be no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be used to force inflate() to return immediately after header processing is complete and before any actual data is decompressed. The text, time, xflags, and os fields are filled in with the gzip header contents. hcrc is set to true if there is a header CRC. (The header CRC was valid if done is set to one.) If extra is not Z_NULL, then extra_max contains the maximum number of bytes to write to extra. Once done is true, extra_len contains the actual extra field length, and extra contains the extra field, or that field truncated if extra_max is less than extra_len. If name is not Z_NULL, then up to name_max characters are written there, terminated with a zero unless the length is greater than name_max. If comment is not Z_NULL, then up to comm_max characters are written there, terminated with a zero unless the length is greater than comm_max. When any of extra, name, or comment are not Z_NULL and the respective field is not present in the header, then that field is set to Z_NULL to signal its absence. This allows the use of deflateSetHeader() with the returned structure to duplicate the header. However if those fields are set to allocated memory, then the application will need to save those pointers elsewhere so that they can be eventually freed. If inflateGetHeader is not used, then the header information is simply discarded. The header is always checked for validity, including the header CRC if present. inflateReset() will reset the process to discard the header information. The application would need to call inflateGetHeader() again to retrieve the header from the next gzip stream. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent. */ /* ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, unsigned char FAR *window)); Initialize the internal stream state for decompression using inflateBack() calls. The fields zalloc, zfree and opaque in strm must be initialized before the call. If zalloc and zfree are Z_NULL, then the default library- derived memory allocation routines are used. windowBits is the base two logarithm of the window size, in the range 8..15. window is a caller supplied buffer of that size. Except for special applications where it is assured that deflate was used with small window sizes, windowBits must be 15 and a 32K byte window must be supplied to be able to decompress general deflate streams. See inflateBack() for the usage of these routines. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of the parameters are invalid, Z_MEM_ERROR if the internal state could not be allocated, or Z_VERSION_ERROR if the version of the library does not match the version of the header file. */ typedef unsigned (*in_func) OF((void FAR *, z_const unsigned char FAR * FAR *)); typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, in_func in, void FAR *in_desc, out_func out, void FAR *out_desc)); /* inflateBack() does a raw inflate with a single call using a call-back interface for input and output. This is potentially more efficient than inflate() for file i/o applications, in that it avoids copying between the output and the sliding window by simply making the window itself the output buffer. inflate() can be faster on modern CPUs when used with large buffers. inflateBack() trusts the application to not change the output buffer passed by the output function, at least until inflateBack() returns. inflateBackInit() must be called first to allocate the internal state and to initialize the state with the user-provided window buffer. inflateBack() may then be used multiple times to inflate a complete, raw deflate stream with each call. inflateBackEnd() is then called to free the allocated state. A raw deflate stream is one with no zlib or gzip header or trailer. This routine would normally be used in a utility that reads zip or gzip files and writes out uncompressed files. The utility would decode the header and process the trailer on its own, hence this routine expects only the raw deflate stream to decompress. This is different from the default behavior of inflate(), which expects a zlib header and trailer around the deflate stream. inflateBack() uses two subroutines supplied by the caller that are then called by inflateBack() for input and output. inflateBack() calls those routines until it reads a complete deflate stream and writes out all of the uncompressed data, or until it encounters an error. The function's parameters and return types are defined above in the in_func and out_func typedefs. inflateBack() will call in(in_desc, &buf) which should return the number of bytes of provided input, and a pointer to that input in buf. If there is no input available, in() must return zero -- buf is ignored in that case -- and inflateBack() will return a buffer error. inflateBack() will call out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() should return zero on success, or non-zero on failure. If out() returns non-zero, inflateBack() will return with an error. Neither in() nor out() are permitted to change the contents of the window provided to inflateBackInit(), which is also the buffer that out() uses to write from. The length written by out() will be at most the window size. Any non-zero amount of input may be provided by in(). For convenience, inflateBack() can be provided input on the first call by setting strm->next_in and strm->avail_in. If that input is exhausted, then in() will be called. Therefore strm->next_in must be initialized before calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in must also be initialized, and then if strm->avail_in is not zero, input will initially be taken from strm->next_in[0 .. strm->avail_in - 1]. The in_desc and out_desc parameters of inflateBack() is passed as the first parameter of in() and out() respectively when they are called. These descriptors can be optionally used to pass any information that the caller- supplied in() and out() functions need to do their job. On return, inflateBack() will set strm->next_in and strm->avail_in to pass back any unused input that was provided by the last in() call. The return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR if in() or out() returned an error, Z_DATA_ERROR if there was a format error in the deflate stream (in which case strm->msg is set to indicate the nature of the error), or Z_STREAM_ERROR if the stream was not properly initialized. In the case of Z_BUF_ERROR, an input or output error can be distinguished using strm->next_in which will be Z_NULL only if in() returned an error. If strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning non-zero. (in() will always be called before out(), so strm->next_in is assured to be defined if out() returns non-zero.) Note that inflateBack() cannot return Z_OK. */ ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); /* All memory allocated by inflateBackInit() is freed. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream state was inconsistent. */ ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); /* Return flags indicating compile-time options. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: 1.0: size of uInt 3.2: size of uLong 5.4: size of voidpf (pointer) 7.6: size of z_off_t Compiler, assembler, and debug options: 8: ZLIB_DEBUG 9: ASMV or ASMINF -- use ASM code 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention 11: 0 (reserved) One-time table building (smaller code, but not thread-safe if true): 12: BUILDFIXED -- build static block decoding tables when needed 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed 14,15: 0 (reserved) Library content (indicates missing functionality): 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking deflate code when not needed) 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect and decode gzip streams (to avoid linking crc code) 18-19: 0 (reserved) Operation variations (changes in library functionality): 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate 21: FASTEST -- deflate algorithm with only one, lowest compression level 22,23: 0 (reserved) The sprintf variant used by gzprintf (zero is best): 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! 26: 0 = returns value, 1 = void -- 1 means inferred string length returned Remainder: 27-31: 0 (reserved) */ #ifndef Z_SOLO /* utility functions */ /* The following utility functions are implemented on top of the basic stream-oriented functions. To simplify the interface, some default options are assumed (compression level and memory usage, standard memory allocation functions). The source code of these utility functions can be modified if you need special options. */ ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)); /* Compresses the source buffer into the destination buffer. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be at least the value returned by compressBound(sourceLen). Upon exit, destLen is the actual size of the compressed data. compress() is equivalent to compress2() with a level parameter of Z_DEFAULT_COMPRESSION. compress returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer. */ ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen, int level)); /* Compresses the source buffer into the destination buffer. The level parameter has the same meaning as in deflateInit. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be at least the value returned by compressBound(sourceLen). Upon exit, destLen is the actual size of the compressed data. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, Z_STREAM_ERROR if the level parameter is invalid. */ ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); /* compressBound() returns an upper bound on the compressed size after compress() or compress2() on sourceLen bytes. It would be used before a compress() or compress2() call to allocate the destination buffer. */ ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)); /* Decompresses the source buffer into the destination buffer. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be large enough to hold the entire uncompressed data. (The size of the uncompressed data must have been saved previously by the compressor and transmitted to the decompressor by some mechanism outside the scope of this compression library.) Upon exit, destLen is the actual size of the uncompressed data. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. In the case where there is not enough room, uncompress() will fill the output buffer with the uncompressed data up to that point. */ ZEXTERN int ZEXPORT uncompress2 OF((Bytef *dest, uLongf *destLen, const Bytef *source, uLong *sourceLen)); /* Same as uncompress, except that sourceLen is a pointer, where the length of the source is *sourceLen. On return, *sourceLen is the number of source bytes consumed. */ /* gzip file access functions */ /* This library supports reading and writing files in gzip (.gz) format with an interface similar to that of stdio, using the functions that start with "gz". The gzip format is different from the zlib format. gzip is a gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. */ typedef struct gzFile_s *gzFile; /* semi-opaque gzip file descriptor */ /* ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); Opens a gzip (.gz) file for reading or writing. The mode parameter is as in fopen ("rb" or "wb") but can also include a compression level ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F' for fixed code compression as in "wb9F". (See the description of deflateInit2 for more information about the strategy parameter.) 'T' will request transparent writing or appending with no compression and not using the gzip format. "a" can be used instead of "w" to request that the gzip stream that will be written be appended to the file. "+" will result in an error, since reading and writing to the same gzip file is not supported. The addition of "x" when writing will create the file exclusively, which fails if the file already exists. On systems that support it, the addition of "e" when reading or writing will set the flag to close the file on an execve() call. These functions, as well as gzip, will read and decode a sequence of gzip streams in a file. The append function of gzopen() can be used to create such a file. (Also see gzflush() for another way to do this.) When appending, gzopen does not test whether the file begins with a gzip stream, nor does it look for the end of the gzip streams to begin appending. gzopen will simply append a gzip stream to the existing file. gzopen can be used to read a file which is not in gzip format; in this case gzread will directly read from the file without decompression. When reading, this will be detected automatically by looking for the magic two- byte gzip header. gzopen returns NULL if the file could not be opened, if there was insufficient memory to allocate the gzFile state, or if an invalid mode was specified (an 'r', 'w', or 'a' was not provided, or '+' was provided). errno can be checked to determine if the reason gzopen failed was that the file could not be opened. */ ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); /* gzdopen associates a gzFile with the file descriptor fd. File descriptors are obtained from calls like open, dup, creat, pipe or fileno (if the file has been previously opened with fopen). The mode parameter is as in gzopen. The next call of gzclose on the returned gzFile will also close the file descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd, mode);. The duplicated descriptor should be saved to avoid a leak, since gzdopen does not close fd if it fails. If you are using fileno() to get the file descriptor from a FILE *, then you will have to use dup() to avoid double-close()ing the file descriptor. Both gzclose() and fclose() will close the associated file descriptor, so they need to have different file descriptors. gzdopen returns NULL if there was insufficient memory to allocate the gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not provided, or '+' was provided), or if fd is -1. The file descriptor is not used until the next gz* read, write, seek, or close operation, so gzdopen will not detect if fd is invalid (unless fd is -1). */ ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size)); /* Set the internal buffer size used by this library's functions. The default buffer size is 8192 bytes. This function must be called after gzopen() or gzdopen(), and before any other calls that read or write the file. The buffer memory allocation is always deferred to the first read or write. Three times that size in buffer space is allocated. A larger buffer size of, for example, 64K or 128K bytes will noticeably increase the speed of decompression (reading). The new buffer size also affects the maximum length for gzprintf(). gzbuffer() returns 0 on success, or -1 on failure, such as being called too late. */ ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); /* Dynamically update the compression level or strategy. See the description of deflateInit2 for the meaning of these parameters. Previously provided data is flushed before the parameter change. gzsetparams returns Z_OK if success, Z_STREAM_ERROR if the file was not opened for writing, Z_ERRNO if there is an error writing the flushed data, or Z_MEM_ERROR if there is a memory allocation error. */ ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); /* Reads the given number of uncompressed bytes from the compressed file. If the input file is not in gzip format, gzread copies the given number of bytes into the buffer directly from the file. After reaching the end of a gzip stream in the input, gzread will continue to read, looking for another gzip stream. Any number of gzip streams may be concatenated in the input file, and will all be decompressed by gzread(). If something other than a gzip stream is encountered after a gzip stream, that remaining trailing garbage is ignored (and no error is returned). gzread can be used to read a gzip file that is being concurrently written. Upon reaching the end of the input, gzread will return with the available data. If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then gzclearerr can be used to clear the end of file indicator in order to permit gzread to be tried again. Z_OK indicates that a gzip stream was completed on the last gzread. Z_BUF_ERROR indicates that the input file ended in the middle of a gzip stream. Note that gzread does not return -1 in the event of an incomplete gzip stream. This error is deferred until gzclose(), which will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip stream. Alternatively, gzerror can be used before gzclose to detect this case. gzread returns the number of uncompressed bytes actually read, less than len for end of file, or -1 for error. If len is too large to fit in an int, then nothing is read, -1 is returned, and the error state is set to Z_STREAM_ERROR. */ ZEXTERN z_size_t ZEXPORT gzfread OF((voidp buf, z_size_t size, z_size_t nitems, gzFile file)); /* Read up to nitems items of size size from file to buf, otherwise operating as gzread() does. This duplicates the interface of stdio's fread(), with size_t request and return types. If the library defines size_t, then z_size_t is identical to size_t. If not, then z_size_t is an unsigned integer type that can contain a pointer. gzfread() returns the number of full items read of size size, or zero if the end of the file was reached and a full item could not be read, or if there was an error. gzerror() must be consulted if zero is returned in order to determine if there was an error. If the multiplication of size and nitems overflows, i.e. the product does not fit in a z_size_t, then nothing is read, zero is returned, and the error state is set to Z_STREAM_ERROR. In the event that the end of file is reached and only a partial item is available at the end, i.e. the remaining uncompressed data length is not a multiple of size, then the final partial item is nevetheless read into buf and the end-of-file flag is set. The length of the partial item read is not provided, but could be inferred from the result of gztell(). This behavior is the same as the behavior of fread() implementations in common libraries, but it prevents the direct use of gzfread() to read a concurrently written file, reseting and retrying on end-of-file, when size is not 1. */ ZEXTERN int ZEXPORT gzwrite OF((gzFile file, voidpc buf, unsigned len)); /* Writes the given number of uncompressed bytes into the compressed file. gzwrite returns the number of uncompressed bytes written or 0 in case of error. */ ZEXTERN z_size_t ZEXPORT gzfwrite OF((voidpc buf, z_size_t size, z_size_t nitems, gzFile file)); /* gzfwrite() writes nitems items of size size from buf to file, duplicating the interface of stdio's fwrite(), with size_t request and return types. If the library defines size_t, then z_size_t is identical to size_t. If not, then z_size_t is an unsigned integer type that can contain a pointer. gzfwrite() returns the number of full items written of size size, or zero if there was an error. If the multiplication of size and nitems overflows, i.e. the product does not fit in a z_size_t, then nothing is written, zero is returned, and the error state is set to Z_STREAM_ERROR. */ ZEXTERN int ZEXPORTVA gzprintf Z_ARG((gzFile file, const char *format, ...)); /* Converts, formats, and writes the arguments to the compressed file under control of the format string, as in fprintf. gzprintf returns the number of uncompressed bytes actually written, or a negative zlib error code in case of error. The number of uncompressed bytes written is limited to 8191, or one less than the buffer size given to gzbuffer(). The caller should assure that this limit is not exceeded. If it is exceeded, then gzprintf() will return an error (0) with nothing written. In this case, there may also be a buffer overflow with unpredictable consequences, which is possible only if zlib was compiled with the insecure functions sprintf() or vsprintf() because the secure snprintf() or vsnprintf() functions were not available. This can be determined using zlibCompileFlags(). */ ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); /* Writes the given null-terminated string to the compressed file, excluding the terminating null character. gzputs returns the number of characters written, or -1 in case of error. */ ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); /* Reads bytes from the compressed file until len-1 characters are read, or a newline character is read and transferred to buf, or an end-of-file condition is encountered. If any characters are read or if len == 1, the string is terminated with a null character. If no characters are read due to an end-of-file or len < 1, then the buffer is left untouched. gzgets returns buf which is a null-terminated string, or it returns NULL for end-of-file or in case of error. If there was an error, the contents at buf are indeterminate. */ ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); /* Writes c, converted to an unsigned char, into the compressed file. gzputc returns the value that was written, or -1 in case of error. */ ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); /* Reads one byte from the compressed file. gzgetc returns this byte or -1 in case of end of file or error. This is implemented as a macro for speed. As such, it does not do all of the checking the other functions do. I.e. it does not check to see if file is NULL, nor whether the structure file points to has been clobbered or not. */ ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); /* Push one character back onto the stream to be read as the first character on the next read. At least one character of push-back is allowed. gzungetc() returns the character pushed, or -1 on failure. gzungetc() will fail if c is -1, and may fail if a character has been pushed but not read yet. If gzungetc is used immediately after gzopen or gzdopen, at least the output buffer size of pushed characters is allowed. (See gzbuffer above.) The pushed character will be discarded if the stream is repositioned with gzseek() or gzrewind(). */ ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); /* Flushes all pending output into the compressed file. The parameter flush is as in the deflate() function. The return value is the zlib error number (see function gzerror below). gzflush is only permitted when writing. If the flush parameter is Z_FINISH, the remaining data is written and the gzip stream is completed in the output. If gzwrite() is called again, a new gzip stream will be started in the output. gzread() is able to read such concatenated gzip streams. gzflush should be called only when strictly necessary because it will degrade compression if called too often. */ /* ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, z_off_t offset, int whence)); Sets the starting position for the next gzread or gzwrite on the given compressed file. The offset represents a number of bytes in the uncompressed data stream. The whence parameter is defined as in lseek(2); the value SEEK_END is not supported. If the file is opened for reading, this function is emulated but can be extremely slow. If the file is opened for writing, only forward seeks are supported; gzseek then compresses a sequence of zeroes up to the new starting position. gzseek returns the resulting offset location as measured in bytes from the beginning of the uncompressed stream, or -1 in case of error, in particular if the file is opened for writing and the new starting position would be before the current position. */ ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); /* Rewinds the given file. This function is supported only for reading. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) */ /* ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); Returns the starting position for the next gzread or gzwrite on the given compressed file. This position represents a number of bytes in the uncompressed data stream, and is zero when starting, even if appending or reading a gzip stream from the middle of a file using gzdopen(). gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) */ /* ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file)); Returns the current offset in the file being read or written. This offset includes the count of bytes that precede the gzip stream, for example when appending or when using gzdopen() for reading. When reading, the offset does not include as yet unused buffered input. This information can be used for a progress indicator. On error, gzoffset() returns -1. */ ZEXTERN int ZEXPORT gzeof OF((gzFile file)); /* Returns true (1) if the end-of-file indicator has been set while reading, false (0) otherwise. Note that the end-of-file indicator is set only if the read tried to go past the end of the input, but came up short. Therefore, just like feof(), gzeof() may return false even if there is no more data to read, in the event that the last read request was for the exact number of bytes remaining in the input file. This will happen if the input file size is an exact multiple of the buffer size. If gzeof() returns true, then the read functions will return no more data, unless the end-of-file indicator is reset by gzclearerr() and the input file has grown since the previous end of file was detected. */ ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); /* Returns true (1) if file is being copied directly while reading, or false (0) if file is a gzip stream being decompressed. If the input file is empty, gzdirect() will return true, since the input does not contain a gzip stream. If gzdirect() is used immediately after gzopen() or gzdopen() it will cause buffers to be allocated to allow reading the file to determine if it is a gzip file. Therefore if gzbuffer() is used, it should be called before gzdirect(). When writing, gzdirect() returns true (1) if transparent writing was requested ("wT" for the gzopen() mode), or false (0) otherwise. (Note: gzdirect() is not needed when writing. Transparent writing must be explicitly requested, so the application already knows the answer. When linking statically, using gzdirect() will include all of the zlib code for gzip file reading and decompression, which may not be desired.) */ ZEXTERN int ZEXPORT gzclose OF((gzFile file)); /* Flushes all pending output if necessary, closes the compressed file and deallocates the (de)compression state. Note that once file is closed, you cannot call gzerror with file, since its structures have been deallocated. gzclose must not be called more than once on the same file, just as free must not be called more than once on the same allocation. gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the last read ended in the middle of a gzip stream, or Z_OK on success. */ ZEXTERN int ZEXPORT gzclose_r OF((gzFile file)); ZEXTERN int ZEXPORT gzclose_w OF((gzFile file)); /* Same as gzclose(), but gzclose_r() is only for use when reading, and gzclose_w() is only for use when writing or appending. The advantage to using these instead of gzclose() is that they avoid linking in zlib compression or decompression code that is not used when only reading or only writing respectively. If gzclose() is used, then both compression and decompression code will be included the application when linking to a static zlib library. */ ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); /* Returns the error message for the last error which occurred on the given compressed file. errnum is set to zlib error number. If an error occurred in the file system and not in the compression library, errnum is set to Z_ERRNO and the application may consult errno to get the exact error code. The application must not modify the returned string. Future calls to this function may invalidate the previously returned string. If file is closed, then the string previously returned by gzerror will no longer be available. gzerror() should be used to distinguish errors from end-of-file for those functions above that do not distinguish those cases in their return values. */ ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); /* Clears the error and end-of-file flags for file. This is analogous to the clearerr() function in stdio. This is useful for continuing to read a gzip file that is being written concurrently. */ #endif /* !Z_SOLO */ /* checksum functions */ /* These functions are not related to compression but are exported anyway because they might be useful in applications using the compression library. */ ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); /* Update a running Adler-32 checksum with the bytes buf[0..len-1] and return the updated checksum. If buf is Z_NULL, this function returns the required initial value for the checksum. An Adler-32 checksum is almost as reliable as a CRC-32 but can be computed much faster. Usage example: uLong adler = adler32(0L, Z_NULL, 0); while (read_buffer(buffer, length) != EOF) { adler = adler32(adler, buffer, length); } if (adler != original_adler) error(); */ ZEXTERN uLong ZEXPORT adler32_z OF((uLong adler, const Bytef *buf, z_size_t len)); /* Same as adler32(), but with a size_t length. */ /* ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, z_off_t len2)); Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. Note that the z_off_t type (like off_t) is a signed integer. If len2 is negative, the result has no meaning or utility. */ ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); /* Update a running CRC-32 with the bytes buf[0..len-1] and return the updated CRC-32. If buf is Z_NULL, this function returns the required initial value for the crc. Pre- and post-conditioning (one's complement) is performed within this function so it shouldn't be done by the application. Usage example: uLong crc = crc32(0L, Z_NULL, 0); while (read_buffer(buffer, length) != EOF) { crc = crc32(crc, buffer, length); } if (crc != original_crc) error(); */ ZEXTERN uLong ZEXPORT crc32_z OF((uLong crc, const Bytef *buf, z_size_t len)); /* Same as crc32(), but with a size_t length. */ /* ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); Combine two CRC-32 check values into one. For two sequences of bytes, seq1 and seq2 with lengths len1 and len2, CRC-32 check values were calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and len2. */ /* various hacks, don't look :) */ /* deflateInit and inflateInit are macros to allow checking the zlib version * and the compiler's view of z_stream: */ ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, const char *version, int stream_size)); ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, const char *version, int stream_size)); ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)); ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, const char *version, int stream_size)); ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, unsigned char FAR *window, const char *version, int stream_size)); #ifdef Z_PREFIX_SET # define z_deflateInit(strm, level) \ deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) # define z_inflateInit(strm) \ inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) # define z_deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) # define z_inflateInit2(strm, windowBits) \ inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ (int)sizeof(z_stream)) # define z_inflateBackInit(strm, windowBits, window) \ inflateBackInit_((strm), (windowBits), (window), \ ZLIB_VERSION, (int)sizeof(z_stream)) #else # define deflateInit(strm, level) \ deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) # define inflateInit(strm) \ inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) # define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) # define inflateInit2(strm, windowBits) \ inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ (int)sizeof(z_stream)) # define inflateBackInit(strm, windowBits, window) \ inflateBackInit_((strm), (windowBits), (window), \ ZLIB_VERSION, (int)sizeof(z_stream)) #endif #ifndef Z_SOLO /* gzgetc() macro and its supporting function and exposed data structure. Note * that the real internal state is much larger than the exposed structure. * This abbreviated structure exposes just enough for the gzgetc() macro. The * user should not mess with these exposed elements, since their names or * behavior could change in the future, perhaps even capriciously. They can * only be used by the gzgetc() macro. You have been warned. */ struct gzFile_s { unsigned have; unsigned char *next; z_off64_t pos; }; ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file)); /* backward compatibility */ #ifdef Z_PREFIX_SET # undef z_gzgetc # define z_gzgetc(g) \ ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) #else # define gzgetc(g) \ ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) #endif /* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if * both are true, the application gets the *64 functions, and the regular * functions are changed to 64 bits) -- in case these are set on systems * without large file support, _LFS64_LARGEFILE must also be true */ #ifdef Z_LARGE64 ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t)); ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t)); #endif #if !defined(ZLIB_INTERNAL) && defined(Z_WANT64) # ifdef Z_PREFIX_SET # define z_gzopen z_gzopen64 # define z_gzseek z_gzseek64 # define z_gztell z_gztell64 # define z_gzoffset z_gzoffset64 # define z_adler32_combine z_adler32_combine64 # define z_crc32_combine z_crc32_combine64 # else # define gzopen gzopen64 # define gzseek gzseek64 # define gztell gztell64 # define gzoffset gzoffset64 # define adler32_combine adler32_combine64 # define crc32_combine crc32_combine64 # endif # ifndef Z_LARGE64 ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int)); ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile)); ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile)); ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); # endif #else ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *)); ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int)); ZEXTERN z_off_t ZEXPORT gztell OF((gzFile)); ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile)); ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); #endif #else /* Z_SOLO */ ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); #endif /* !Z_SOLO */ /* undocumented functions */ ZEXTERN const char * ZEXPORT zError OF((int)); ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp)); ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table OF((void)); ZEXTERN int ZEXPORT inflateUndermine OF((z_streamp, int)); ZEXTERN int ZEXPORT inflateValidate OF((z_streamp, int)); ZEXTERN unsigned long ZEXPORT inflateCodesUsed OF ((z_streamp)); ZEXTERN int ZEXPORT inflateResetKeep OF((z_streamp)); ZEXTERN int ZEXPORT deflateResetKeep OF((z_streamp)); #if defined(_WIN32) && !defined(Z_SOLO) ZEXTERN gzFile ZEXPORT gzopen_w OF((const wchar_t *path, const char *mode)); #endif #if defined(STDC) || defined(Z_HAVE_STDARG_H) # ifndef Z_SOLO ZEXTERN int ZEXPORTVA gzvprintf Z_ARG((gzFile file, const char *format, va_list va)); # endif #endif #ifdef __cplusplus } #endif #endif /* ZLIB_H */
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/tests/Interop/PInvoke/SizeParamIndex/ReversePInvoke/PassingByOut/CMakeLists.txt
project (RPIP_ByOutNative) include ("${CLR_INTEROP_TEST_ROOT}/Interop.cmake") include_directories("..") set(SOURCES ReversePInvokePassingByOutNative.cpp ) # Additional files to reference: # add the executable add_library (RPIP_ByOutNative SHARED ${SOURCES}) set_property (TARGET RPIP_ByOutNative PROPERTY OUTPUT_NAME ReversePInvokePassingByOutNative) target_link_libraries(RPIP_ByOutNative ${LINK_LIBRARIES_ADDITIONAL}) # add the install targets install (TARGETS RPIP_ByOutNative DESTINATION bin)
project (RPIP_ByOutNative) include ("${CLR_INTEROP_TEST_ROOT}/Interop.cmake") include_directories("..") set(SOURCES ReversePInvokePassingByOutNative.cpp ) # Additional files to reference: # add the executable add_library (RPIP_ByOutNative SHARED ${SOURCES}) set_property (TARGET RPIP_ByOutNative PROPERTY OUTPUT_NAME ReversePInvokePassingByOutNative) target_link_libraries(RPIP_ByOutNative ${LINK_LIBRARIES_ADDITIONAL}) # add the install targets install (TARGETS RPIP_ByOutNative DESTINATION bin)
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/native/external/rapidjson/memorybuffer.h
// Tencent is pleased to support the open source community by making RapidJSON available. // // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. // // Licensed under the MIT License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://opensource.org/licenses/MIT // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #ifndef RAPIDJSON_MEMORYBUFFER_H_ #define RAPIDJSON_MEMORYBUFFER_H_ #include "stream.h" #include "internal/stack.h" RAPIDJSON_NAMESPACE_BEGIN //! Represents an in-memory output byte stream. /*! This class is mainly for being wrapped by EncodedOutputStream or AutoUTFOutputStream. It is similar to FileWriteBuffer but the destination is an in-memory buffer instead of a file. Differences between MemoryBuffer and StringBuffer: 1. StringBuffer has Encoding but MemoryBuffer is only a byte buffer. 2. StringBuffer::GetString() returns a null-terminated string. MemoryBuffer::GetBuffer() returns a buffer without terminator. \tparam Allocator type for allocating memory buffer. \note implements Stream concept */ template <typename Allocator = CrtAllocator> struct GenericMemoryBuffer { typedef char Ch; // byte GenericMemoryBuffer(Allocator* allocator = 0, size_t capacity = kDefaultCapacity) : stack_(allocator, capacity) {} void Put(Ch c) { *stack_.template Push<Ch>() = c; } void Flush() {} void Clear() { stack_.Clear(); } void ShrinkToFit() { stack_.ShrinkToFit(); } Ch* Push(size_t count) { return stack_.template Push<Ch>(count); } void Pop(size_t count) { stack_.template Pop<Ch>(count); } const Ch* GetBuffer() const { return stack_.template Bottom<Ch>(); } size_t GetSize() const { return stack_.GetSize(); } static const size_t kDefaultCapacity = 256; mutable internal::Stack<Allocator> stack_; }; typedef GenericMemoryBuffer<> MemoryBuffer; //! Implement specialized version of PutN() with memset() for better performance. template<> inline void PutN(MemoryBuffer& memoryBuffer, char c, size_t n) { std::memset(memoryBuffer.stack_.Push<char>(n), c, n * sizeof(c)); } RAPIDJSON_NAMESPACE_END #endif // RAPIDJSON_MEMORYBUFFER_H_
// Tencent is pleased to support the open source community by making RapidJSON available. // // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. // // Licensed under the MIT License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://opensource.org/licenses/MIT // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #ifndef RAPIDJSON_MEMORYBUFFER_H_ #define RAPIDJSON_MEMORYBUFFER_H_ #include "stream.h" #include "internal/stack.h" RAPIDJSON_NAMESPACE_BEGIN //! Represents an in-memory output byte stream. /*! This class is mainly for being wrapped by EncodedOutputStream or AutoUTFOutputStream. It is similar to FileWriteBuffer but the destination is an in-memory buffer instead of a file. Differences between MemoryBuffer and StringBuffer: 1. StringBuffer has Encoding but MemoryBuffer is only a byte buffer. 2. StringBuffer::GetString() returns a null-terminated string. MemoryBuffer::GetBuffer() returns a buffer without terminator. \tparam Allocator type for allocating memory buffer. \note implements Stream concept */ template <typename Allocator = CrtAllocator> struct GenericMemoryBuffer { typedef char Ch; // byte GenericMemoryBuffer(Allocator* allocator = 0, size_t capacity = kDefaultCapacity) : stack_(allocator, capacity) {} void Put(Ch c) { *stack_.template Push<Ch>() = c; } void Flush() {} void Clear() { stack_.Clear(); } void ShrinkToFit() { stack_.ShrinkToFit(); } Ch* Push(size_t count) { return stack_.template Push<Ch>(count); } void Pop(size_t count) { stack_.template Pop<Ch>(count); } const Ch* GetBuffer() const { return stack_.template Bottom<Ch>(); } size_t GetSize() const { return stack_.GetSize(); } static const size_t kDefaultCapacity = 256; mutable internal::Stack<Allocator> stack_; }; typedef GenericMemoryBuffer<> MemoryBuffer; //! Implement specialized version of PutN() with memset() for better performance. template<> inline void PutN(MemoryBuffer& memoryBuffer, char c, size_t n) { std::memset(memoryBuffer.stack_.Push<char>(n), c, n * sizeof(c)); } RAPIDJSON_NAMESPACE_END #endif // RAPIDJSON_MEMORYBUFFER_H_
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/xsltc/baseline/sft31.txt
<?xml version="1.0" encoding="utf-8"?><out>John Doe</out>
<?xml version="1.0" encoding="utf-8"?><out>John Doe</out>
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/xsltc/baseline/oft25.txt
<?xml version="1.0" encoding="utf-8"?>Hello, world!
<?xml version="1.0" encoding="utf-8"?>Hello, world!
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/xsltc/baseline/cnt28.txt
<?xml version="1.0" encoding="utf-8"?>Hello, world!
<?xml version="1.0" encoding="utf-8"?>Hello, world!
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/tests/Interop/IJW/IjwNativeDll/CMakeLists.txt
project (IjwNativeDll) include("../IJW.cmake") include_directories( ${INC_PLATFORM_DIR} ) set(SOURCES IjwNativeDll.cpp) # add the shared library add_library (IjwNativeDll SHARED ${SOURCES}) target_link_libraries(IjwNativeDll ${LINK_LIBRARIES_ADDITIONAL}) # add the install targets install (TARGETS IjwNativeDll DESTINATION bin)
project (IjwNativeDll) include("../IJW.cmake") include_directories( ${INC_PLATFORM_DIR} ) set(SOURCES IjwNativeDll.cpp) # add the shared library add_library (IjwNativeDll SHARED ${SOURCES}) target_link_libraries(IjwNativeDll ${LINK_LIBRARIES_ADDITIONAL}) # add the install targets install (TARGETS IjwNativeDll DESTINATION bin)
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/native/external/brotli/enc/bit_cost.c
/* Copyright 2013 Google Inc. All Rights Reserved. Distributed under MIT license. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT */ /* Functions to estimate the bit cost of Huffman trees. */ #include "./bit_cost.h" #include "../common/constants.h" #include "../common/platform.h" #include <brotli/types.h> #include "./fast_log.h" #include "./histogram.h" #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #define FN(X) X ## Literal #include "./bit_cost_inc.h" /* NOLINT(build/include) */ #undef FN #define FN(X) X ## Command #include "./bit_cost_inc.h" /* NOLINT(build/include) */ #undef FN #define FN(X) X ## Distance #include "./bit_cost_inc.h" /* NOLINT(build/include) */ #undef FN #if defined(__cplusplus) || defined(c_plusplus) } /* extern "C" */ #endif
/* Copyright 2013 Google Inc. All Rights Reserved. Distributed under MIT license. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT */ /* Functions to estimate the bit cost of Huffman trees. */ #include "./bit_cost.h" #include "../common/constants.h" #include "../common/platform.h" #include <brotli/types.h> #include "./fast_log.h" #include "./histogram.h" #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #define FN(X) X ## Literal #include "./bit_cost_inc.h" /* NOLINT(build/include) */ #undef FN #define FN(X) X ## Command #include "./bit_cost_inc.h" /* NOLINT(build/include) */ #undef FN #define FN(X) X ## Distance #include "./bit_cost_inc.h" /* NOLINT(build/include) */ #undef FN #if defined(__cplusplus) || defined(c_plusplus) } /* extern "C" */ #endif
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/libraries/System.Management/tests/System/Management/SelectQueryTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Management; using Xunit; namespace System.Management.Tests { public class SelectQueryTests { [ConditionalFact(typeof(WmiTestHelper), nameof(WmiTestHelper.IsWmiSupported))] [ActiveIssue("https://github.com/dotnet/runtime/issues/34689", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] public void Select_Win32_LogicalDisk_ClassName() { var query = new SelectQuery("Win32_LogicalDisk"); var scope = new ManagementScope($@"\\{WmiTestHelper.TargetMachine}\root\cimv2"); scope.Connect(); using (var searcher = new ManagementObjectSearcher(scope, query)) using (var collection = searcher.Get()) { Assert.True(collection.Count > 0); foreach (ManagementBaseObject result in collection) { Assert.True(result.Properties.Count > 1); Assert.True(!string.IsNullOrEmpty(result.Properties["DeviceID"].Value.ToString())); } } } [ConditionalFact(typeof(WmiTestHelper), nameof(WmiTestHelper.IsWmiSupported))] [ActiveIssue("https://github.com/dotnet/runtime/issues/34689", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] public void Select_Win32_LogicalDisk_ClassName_Condition() { var query = new SelectQuery("Win32_LogicalDisk", "DriveType=3"); var scope = new ManagementScope($@"\\{WmiTestHelper.TargetMachine}\root\cimv2"); scope.Connect(); using (var searcher = new ManagementObjectSearcher(scope, query)) using (ManagementObjectCollection collection = searcher.Get()) { Assert.True(collection.Count > 0); foreach (ManagementBaseObject result in collection) { Assert.True(!string.IsNullOrEmpty(result.GetPropertyValue("DeviceID").ToString())); } } } [ConditionalTheory(typeof(WmiTestHelper), nameof(WmiTestHelper.IsWmiSupported))] [ActiveIssue("https://github.com/dotnet/runtime/issues/34689", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] [MemberData(nameof(WmiTestHelper.ScopeRoots), MemberType = typeof(WmiTestHelper))] public void Select_All_Win32_LogicalDisk_Wql(string scopeRoot) { var query = new SelectQuery("select * from Win32_LogicalDisk"); var scope = new ManagementScope(scopeRoot + @"root\cimv2"); scope.Connect(); using (var searcher = new ManagementObjectSearcher(scope, query)) using (ManagementObjectCollection collection = searcher.Get()) { Assert.True(collection.Count > 0); foreach (ManagementBaseObject result in collection) { Assert.True(!string.IsNullOrEmpty(result.GetPropertyValue("DeviceID").ToString())); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Management; using Xunit; namespace System.Management.Tests { public class SelectQueryTests { [ConditionalFact(typeof(WmiTestHelper), nameof(WmiTestHelper.IsWmiSupported))] [ActiveIssue("https://github.com/dotnet/runtime/issues/34689", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] public void Select_Win32_LogicalDisk_ClassName() { var query = new SelectQuery("Win32_LogicalDisk"); var scope = new ManagementScope($@"\\{WmiTestHelper.TargetMachine}\root\cimv2"); scope.Connect(); using (var searcher = new ManagementObjectSearcher(scope, query)) using (var collection = searcher.Get()) { Assert.True(collection.Count > 0); foreach (ManagementBaseObject result in collection) { Assert.True(result.Properties.Count > 1); Assert.True(!string.IsNullOrEmpty(result.Properties["DeviceID"].Value.ToString())); } } } [ConditionalFact(typeof(WmiTestHelper), nameof(WmiTestHelper.IsWmiSupported))] [ActiveIssue("https://github.com/dotnet/runtime/issues/34689", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] public void Select_Win32_LogicalDisk_ClassName_Condition() { var query = new SelectQuery("Win32_LogicalDisk", "DriveType=3"); var scope = new ManagementScope($@"\\{WmiTestHelper.TargetMachine}\root\cimv2"); scope.Connect(); using (var searcher = new ManagementObjectSearcher(scope, query)) using (ManagementObjectCollection collection = searcher.Get()) { Assert.True(collection.Count > 0); foreach (ManagementBaseObject result in collection) { Assert.True(!string.IsNullOrEmpty(result.GetPropertyValue("DeviceID").ToString())); } } } [ConditionalTheory(typeof(WmiTestHelper), nameof(WmiTestHelper.IsWmiSupported))] [ActiveIssue("https://github.com/dotnet/runtime/issues/34689", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] [MemberData(nameof(WmiTestHelper.ScopeRoots), MemberType = typeof(WmiTestHelper))] public void Select_All_Win32_LogicalDisk_Wql(string scopeRoot) { var query = new SelectQuery("select * from Win32_LogicalDisk"); var scope = new ManagementScope(scopeRoot + @"root\cimv2"); scope.Connect(); using (var searcher = new ManagementObjectSearcher(scope, query)) using (ManagementObjectCollection collection = searcher.Get()) { Assert.True(collection.Count > 0); foreach (ManagementBaseObject result in collection) { Assert.True(!string.IsNullOrEmpty(result.GetPropertyValue("DeviceID").ToString())); } } } } }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/XsltScenarios/Schematron/v1Test1.txt
In pattern (@Title = 'Mr' and ex:Gender = 'Male') or @Title != 'Mr': If the Title is "Mr" then the gender of the person must be "Male".
In pattern (@Title = 'Mr' and ex:Gender = 'Male') or @Title != 'Mr': If the Title is "Mr" then the gender of the person must be "Male".
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/libraries/System.ServiceModel.Syndication/tests/TestFeeds/AtomFeeds/extensive-nowarn.xml
<!-- Description: No errors should be produced by the extensive feed Expect: !Warning --> <feed xmlns="http://www.w3.org/2005/Atom"> <title type="text">dive into mark</title> <subtitle type="html"> A &lt;em&gt;lot&lt;/em&gt; of effort went into making this effortless </subtitle> <updated>2005-07-11T12:29:29Z</updated> <id>tag:contoso.com,2003:3</id> <link rel="alternate" type="text/html" hreflang="en" href="http://contoso.com/"/> <link rel="self" type="application/atom+xml" href="http://www.contoso.com/testcases/atom/1.1/extensive-nowarn.xml"/> <rights>Copyright (c) 2003, Author Name</rights> <generator uri="http://www.contoso.com/" version="1.0"> Example Toolkit </generator> <entry> <title>Atom draft-07 snapshot</title> <link rel="alternate" type="text/html" href="http://contoso.com/2005/04/02/atom"/> <link rel="enclosure" type="audio/mpeg" length="1337" href="http://contoso.com/audio/ph34r_my_podcast.mp3"/> <id>tag:contoso.com,2003:3.2397</id> <updated>2005-07-11T12:29:29Z</updated> <published>2003-12-13T08:29:29-04:00</published> <author> <name>Author Name</name> <uri>http://contoso.com/</uri> <email>[email protected]</email> </author> <contributor> <name>input name</name> </contributor> <contributor> <name>Name</name> </contributor> <content type="xhtml" xml:lang="en" xml:base="http://contoso.com/"> <div xmlns="http://www.w3.org/1999/xhtml"> <p><i>[Update: The Atom draft is finished.]</i></p> </div> </content> </entry> </feed>
<!-- Description: No errors should be produced by the extensive feed Expect: !Warning --> <feed xmlns="http://www.w3.org/2005/Atom"> <title type="text">dive into mark</title> <subtitle type="html"> A &lt;em&gt;lot&lt;/em&gt; of effort went into making this effortless </subtitle> <updated>2005-07-11T12:29:29Z</updated> <id>tag:contoso.com,2003:3</id> <link rel="alternate" type="text/html" hreflang="en" href="http://contoso.com/"/> <link rel="self" type="application/atom+xml" href="http://www.contoso.com/testcases/atom/1.1/extensive-nowarn.xml"/> <rights>Copyright (c) 2003, Author Name</rights> <generator uri="http://www.contoso.com/" version="1.0"> Example Toolkit </generator> <entry> <title>Atom draft-07 snapshot</title> <link rel="alternate" type="text/html" href="http://contoso.com/2005/04/02/atom"/> <link rel="enclosure" type="audio/mpeg" length="1337" href="http://contoso.com/audio/ph34r_my_podcast.mp3"/> <id>tag:contoso.com,2003:3.2397</id> <updated>2005-07-11T12:29:29Z</updated> <published>2003-12-13T08:29:29-04:00</published> <author> <name>Author Name</name> <uri>http://contoso.com/</uri> <email>[email protected]</email> </author> <contributor> <name>input name</name> </contributor> <contributor> <name>Name</name> </contributor> <content type="xhtml" xml:lang="en" xml:base="http://contoso.com/"> <div xmlns="http://www.w3.org/1999/xhtml"> <p><i>[Update: The Atom draft is finished.]</i></p> </div> </content> </entry> </feed>
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/TypeInfos/NativeFormat/NativeFormatRuntimeNamedTypeInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Text; using System.Reflection; using System.Diagnostics; using System.Collections.Generic; using System.Reflection.Runtime.Assemblies; using System.Reflection.Runtime.General; using System.Reflection.Runtime.CustomAttributes; using Internal.Reflection.Tracing; using Internal.Metadata.NativeFormat; namespace System.Reflection.Runtime.TypeInfos.NativeFormat { internal sealed partial class NativeFormatRuntimeNamedTypeInfo : RuntimeNamedTypeInfo { private NativeFormatRuntimeNamedTypeInfo(MetadataReader reader, TypeDefinitionHandle typeDefinitionHandle, RuntimeTypeHandle typeHandle) : base(typeHandle) { _reader = reader; _typeDefinitionHandle = typeDefinitionHandle; _typeDefinition = _typeDefinitionHandle.GetTypeDefinition(reader); } public sealed override Assembly Assembly { get { // If an assembly is split across multiple metadata blobs then the defining scope may // not be the canonical scope representing the assembly. We need to look up the assembly // by name to ensure we get the right one. ScopeDefinitionHandle scopeDefinitionHandle = NamespaceChain.DefiningScope; RuntimeAssemblyName runtimeAssemblyName = scopeDefinitionHandle.ToRuntimeAssemblyName(_reader); return RuntimeAssemblyInfo.GetRuntimeAssembly(runtimeAssemblyName); } } protected sealed override Guid? ComputeGuidFromCustomAttributes() { // // Look for a [Guid] attribute. If found, return that. // foreach (CustomAttributeHandle cah in _typeDefinition.CustomAttributes) { // We can't reference the GuidAttribute class directly as we don't have an official dependency on System.Runtime.InteropServices. // Following age-old CLR tradition, we search for the custom attribute using a name-based search. Since this makes it harder // to be sure we won't run into custom attribute constructors that comply with the GuidAttribute(String) signature, // we'll check that it does and silently skip the CA if it doesn't match the expected pattern. if (cah.IsCustomAttributeOfType(_reader, "System.Runtime.InteropServices", "GuidAttribute")) { CustomAttribute ca = cah.GetCustomAttribute(_reader); HandleCollection.Enumerator fahEnumerator = ca.FixedArguments.GetEnumerator(); if (!fahEnumerator.MoveNext()) continue; Handle guidStringArgumentHandle = fahEnumerator.Current; if (fahEnumerator.MoveNext()) continue; if (!(guidStringArgumentHandle.ParseConstantValue(_reader) is string guidString)) continue; return new Guid(guidString); } } return null; } protected sealed override void GetPackSizeAndSize(out int packSize, out int size) { packSize = _typeDefinition.PackingSize; size = unchecked((int)(_typeDefinition.Size)); } public sealed override bool IsGenericTypeDefinition { get { return _typeDefinition.GenericParameters.GetEnumerator().MoveNext(); } } public sealed override string Namespace { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_Namespace(this); #endif return NamespaceChain.NameSpace.EscapeTypeNameIdentifier(); } } public sealed override Type GetGenericTypeDefinition() { if (_typeDefinition.GenericParameters.GetEnumerator().MoveNext()) return this; return base.GetGenericTypeDefinition(); } public sealed override int MetadataToken { get { throw new InvalidOperationException(SR.NoMetadataTokenAvailable); } } public sealed override string ToString() { StringBuilder sb = null; foreach (GenericParameterHandle genericParameterHandle in _typeDefinition.GenericParameters) { if (sb == null) { sb = new StringBuilder(FullName); sb.Append('['); } else { sb.Append(','); } sb.Append(genericParameterHandle.GetGenericParameter(_reader).Name.GetString(_reader)); } if (sb == null) { return FullName; } else { return sb.Append(']').ToString(); } } protected sealed override TypeAttributes GetAttributeFlagsImpl() { TypeAttributes attr = _typeDefinition.Flags; return attr; } protected sealed override int InternalGetHashCode() { return _typeDefinitionHandle.GetHashCode(); } internal sealed override Type InternalDeclaringType { get { RuntimeTypeInfo declaringType = null; TypeDefinitionHandle enclosingTypeDefHandle = _typeDefinition.EnclosingType; if (!enclosingTypeDefHandle.IsNull(_reader)) { declaringType = enclosingTypeDefHandle.ResolveTypeDefinition(_reader); } return declaringType; } } internal sealed override string InternalFullNameOfAssembly { get { NamespaceChain namespaceChain = NamespaceChain; ScopeDefinitionHandle scopeDefinitionHandle = namespaceChain.DefiningScope; return scopeDefinitionHandle.ToRuntimeAssemblyName(_reader).FullName; } } public sealed override string InternalGetNameIfAvailable(ref Type rootCauseForFailure) { ConstantStringValueHandle nameHandle = _typeDefinition.Name; string name = nameHandle.GetString(_reader); return name.EscapeTypeNameIdentifier(); } protected sealed override IEnumerable<CustomAttributeData> TrueCustomAttributes => RuntimeCustomAttributeData.GetCustomAttributes(_reader, _typeDefinition.CustomAttributes); internal sealed override RuntimeTypeInfo[] RuntimeGenericTypeParameters { get { LowLevelList<RuntimeTypeInfo> genericTypeParameters = new LowLevelList<RuntimeTypeInfo>(); foreach (GenericParameterHandle genericParameterHandle in _typeDefinition.GenericParameters) { RuntimeTypeInfo genericParameterType = NativeFormat.NativeFormatRuntimeGenericParameterTypeInfoForTypes.GetRuntimeGenericParameterTypeInfoForTypes(this, genericParameterHandle); genericTypeParameters.Add(genericParameterType); } return genericTypeParameters.ToArray(); } } // // Returns the base type as a typeDef, Ref, or Spec. Default behavior is to QTypeDefRefOrSpec.Null, which causes BaseType to return null. // internal sealed override QTypeDefRefOrSpec TypeRefDefOrSpecForBaseType { get { Handle baseType = _typeDefinition.BaseType; if (baseType.IsNull(_reader)) return QTypeDefRefOrSpec.Null; return new QTypeDefRefOrSpec(_reader, baseType); } } // // Returns the *directly implemented* interfaces as typedefs, specs or refs. ImplementedInterfaces will take care of the transitive closure and // insertion of the TypeContext. // internal sealed override QTypeDefRefOrSpec[] TypeRefDefOrSpecsForDirectlyImplementedInterfaces { get { LowLevelList<QTypeDefRefOrSpec> directlyImplementedInterfaces = new LowLevelList<QTypeDefRefOrSpec>(); foreach (Handle ifcHandle in _typeDefinition.Interfaces) directlyImplementedInterfaces.Add(new QTypeDefRefOrSpec(_reader, ifcHandle)); return directlyImplementedInterfaces.ToArray(); } } internal MetadataReader Reader { get { return _reader; } } internal TypeDefinitionHandle TypeDefinitionHandle { get { return _typeDefinitionHandle; } } internal EventHandleCollection DeclaredEventHandles { get { return _typeDefinition.Events; } } internal FieldHandleCollection DeclaredFieldHandles { get { return _typeDefinition.Fields; } } internal MethodHandleCollection DeclaredMethodAndConstructorHandles { get { return _typeDefinition.Methods; } } internal PropertyHandleCollection DeclaredPropertyHandles { get { return _typeDefinition.Properties; } } public bool Equals(NativeFormatRuntimeNamedTypeInfo other) { // RuntimeTypeInfo.Equals(object) is the one that encapsulates our unification strategy so defer to him. object otherAsObject = other; return base.Equals(otherAsObject); } #if ENABLE_REFLECTION_TRACE internal sealed override string TraceableTypeName { get { MetadataReader reader = Reader; String s = ""; TypeDefinitionHandle typeDefinitionHandle = TypeDefinitionHandle; do { TypeDefinition typeDefinition = typeDefinitionHandle.GetTypeDefinition(reader); String name = typeDefinition.Name.GetString(reader); if (s == "") s = name; else s = name + "+" + s; typeDefinitionHandle = typeDefinition.EnclosingType; } while (!typeDefinitionHandle.IsNull(reader)); String ns = NamespaceChain.NameSpace; if (ns != null) s = ns + "." + s; return s; } } #endif internal sealed override QTypeDefRefOrSpec TypeDefinitionQHandle { get { return new QTypeDefRefOrSpec(_reader, _typeDefinitionHandle, true); } } private readonly MetadataReader _reader; private readonly TypeDefinitionHandle _typeDefinitionHandle; private readonly TypeDefinition _typeDefinition; private NamespaceChain NamespaceChain { get { if (_lazyNamespaceChain == null) _lazyNamespaceChain = new NamespaceChain(_reader, _typeDefinition.NamespaceDefinition); return _lazyNamespaceChain; } } private volatile NamespaceChain _lazyNamespaceChain; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Text; using System.Reflection; using System.Diagnostics; using System.Collections.Generic; using System.Reflection.Runtime.Assemblies; using System.Reflection.Runtime.General; using System.Reflection.Runtime.CustomAttributes; using Internal.Reflection.Tracing; using Internal.Metadata.NativeFormat; namespace System.Reflection.Runtime.TypeInfos.NativeFormat { internal sealed partial class NativeFormatRuntimeNamedTypeInfo : RuntimeNamedTypeInfo { private NativeFormatRuntimeNamedTypeInfo(MetadataReader reader, TypeDefinitionHandle typeDefinitionHandle, RuntimeTypeHandle typeHandle) : base(typeHandle) { _reader = reader; _typeDefinitionHandle = typeDefinitionHandle; _typeDefinition = _typeDefinitionHandle.GetTypeDefinition(reader); } public sealed override Assembly Assembly { get { // If an assembly is split across multiple metadata blobs then the defining scope may // not be the canonical scope representing the assembly. We need to look up the assembly // by name to ensure we get the right one. ScopeDefinitionHandle scopeDefinitionHandle = NamespaceChain.DefiningScope; RuntimeAssemblyName runtimeAssemblyName = scopeDefinitionHandle.ToRuntimeAssemblyName(_reader); return RuntimeAssemblyInfo.GetRuntimeAssembly(runtimeAssemblyName); } } protected sealed override Guid? ComputeGuidFromCustomAttributes() { // // Look for a [Guid] attribute. If found, return that. // foreach (CustomAttributeHandle cah in _typeDefinition.CustomAttributes) { // We can't reference the GuidAttribute class directly as we don't have an official dependency on System.Runtime.InteropServices. // Following age-old CLR tradition, we search for the custom attribute using a name-based search. Since this makes it harder // to be sure we won't run into custom attribute constructors that comply with the GuidAttribute(String) signature, // we'll check that it does and silently skip the CA if it doesn't match the expected pattern. if (cah.IsCustomAttributeOfType(_reader, "System.Runtime.InteropServices", "GuidAttribute")) { CustomAttribute ca = cah.GetCustomAttribute(_reader); HandleCollection.Enumerator fahEnumerator = ca.FixedArguments.GetEnumerator(); if (!fahEnumerator.MoveNext()) continue; Handle guidStringArgumentHandle = fahEnumerator.Current; if (fahEnumerator.MoveNext()) continue; if (!(guidStringArgumentHandle.ParseConstantValue(_reader) is string guidString)) continue; return new Guid(guidString); } } return null; } protected sealed override void GetPackSizeAndSize(out int packSize, out int size) { packSize = _typeDefinition.PackingSize; size = unchecked((int)(_typeDefinition.Size)); } public sealed override bool IsGenericTypeDefinition { get { return _typeDefinition.GenericParameters.GetEnumerator().MoveNext(); } } public sealed override string Namespace { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_Namespace(this); #endif return NamespaceChain.NameSpace.EscapeTypeNameIdentifier(); } } public sealed override Type GetGenericTypeDefinition() { if (_typeDefinition.GenericParameters.GetEnumerator().MoveNext()) return this; return base.GetGenericTypeDefinition(); } public sealed override int MetadataToken { get { throw new InvalidOperationException(SR.NoMetadataTokenAvailable); } } public sealed override string ToString() { StringBuilder sb = null; foreach (GenericParameterHandle genericParameterHandle in _typeDefinition.GenericParameters) { if (sb == null) { sb = new StringBuilder(FullName); sb.Append('['); } else { sb.Append(','); } sb.Append(genericParameterHandle.GetGenericParameter(_reader).Name.GetString(_reader)); } if (sb == null) { return FullName; } else { return sb.Append(']').ToString(); } } protected sealed override TypeAttributes GetAttributeFlagsImpl() { TypeAttributes attr = _typeDefinition.Flags; return attr; } protected sealed override int InternalGetHashCode() { return _typeDefinitionHandle.GetHashCode(); } internal sealed override Type InternalDeclaringType { get { RuntimeTypeInfo declaringType = null; TypeDefinitionHandle enclosingTypeDefHandle = _typeDefinition.EnclosingType; if (!enclosingTypeDefHandle.IsNull(_reader)) { declaringType = enclosingTypeDefHandle.ResolveTypeDefinition(_reader); } return declaringType; } } internal sealed override string InternalFullNameOfAssembly { get { NamespaceChain namespaceChain = NamespaceChain; ScopeDefinitionHandle scopeDefinitionHandle = namespaceChain.DefiningScope; return scopeDefinitionHandle.ToRuntimeAssemblyName(_reader).FullName; } } public sealed override string InternalGetNameIfAvailable(ref Type rootCauseForFailure) { ConstantStringValueHandle nameHandle = _typeDefinition.Name; string name = nameHandle.GetString(_reader); return name.EscapeTypeNameIdentifier(); } protected sealed override IEnumerable<CustomAttributeData> TrueCustomAttributes => RuntimeCustomAttributeData.GetCustomAttributes(_reader, _typeDefinition.CustomAttributes); internal sealed override RuntimeTypeInfo[] RuntimeGenericTypeParameters { get { LowLevelList<RuntimeTypeInfo> genericTypeParameters = new LowLevelList<RuntimeTypeInfo>(); foreach (GenericParameterHandle genericParameterHandle in _typeDefinition.GenericParameters) { RuntimeTypeInfo genericParameterType = NativeFormat.NativeFormatRuntimeGenericParameterTypeInfoForTypes.GetRuntimeGenericParameterTypeInfoForTypes(this, genericParameterHandle); genericTypeParameters.Add(genericParameterType); } return genericTypeParameters.ToArray(); } } // // Returns the base type as a typeDef, Ref, or Spec. Default behavior is to QTypeDefRefOrSpec.Null, which causes BaseType to return null. // internal sealed override QTypeDefRefOrSpec TypeRefDefOrSpecForBaseType { get { Handle baseType = _typeDefinition.BaseType; if (baseType.IsNull(_reader)) return QTypeDefRefOrSpec.Null; return new QTypeDefRefOrSpec(_reader, baseType); } } // // Returns the *directly implemented* interfaces as typedefs, specs or refs. ImplementedInterfaces will take care of the transitive closure and // insertion of the TypeContext. // internal sealed override QTypeDefRefOrSpec[] TypeRefDefOrSpecsForDirectlyImplementedInterfaces { get { LowLevelList<QTypeDefRefOrSpec> directlyImplementedInterfaces = new LowLevelList<QTypeDefRefOrSpec>(); foreach (Handle ifcHandle in _typeDefinition.Interfaces) directlyImplementedInterfaces.Add(new QTypeDefRefOrSpec(_reader, ifcHandle)); return directlyImplementedInterfaces.ToArray(); } } internal MetadataReader Reader { get { return _reader; } } internal TypeDefinitionHandle TypeDefinitionHandle { get { return _typeDefinitionHandle; } } internal EventHandleCollection DeclaredEventHandles { get { return _typeDefinition.Events; } } internal FieldHandleCollection DeclaredFieldHandles { get { return _typeDefinition.Fields; } } internal MethodHandleCollection DeclaredMethodAndConstructorHandles { get { return _typeDefinition.Methods; } } internal PropertyHandleCollection DeclaredPropertyHandles { get { return _typeDefinition.Properties; } } public bool Equals(NativeFormatRuntimeNamedTypeInfo other) { // RuntimeTypeInfo.Equals(object) is the one that encapsulates our unification strategy so defer to him. object otherAsObject = other; return base.Equals(otherAsObject); } #if ENABLE_REFLECTION_TRACE internal sealed override string TraceableTypeName { get { MetadataReader reader = Reader; String s = ""; TypeDefinitionHandle typeDefinitionHandle = TypeDefinitionHandle; do { TypeDefinition typeDefinition = typeDefinitionHandle.GetTypeDefinition(reader); String name = typeDefinition.Name.GetString(reader); if (s == "") s = name; else s = name + "+" + s; typeDefinitionHandle = typeDefinition.EnclosingType; } while (!typeDefinitionHandle.IsNull(reader)); String ns = NamespaceChain.NameSpace; if (ns != null) s = ns + "." + s; return s; } } #endif internal sealed override QTypeDefRefOrSpec TypeDefinitionQHandle { get { return new QTypeDefRefOrSpec(_reader, _typeDefinitionHandle, true); } } private readonly MetadataReader _reader; private readonly TypeDefinitionHandle _typeDefinitionHandle; private readonly TypeDefinition _typeDefinition; private NamespaceChain NamespaceChain { get { if (_lazyNamespaceChain == null) _lazyNamespaceChain = new NamespaceChain(_reader, _typeDefinition.NamespaceDefinition); return _lazyNamespaceChain; } } private volatile NamespaceChain _lazyNamespaceChain; } }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/tests/JIT/Directed/PREFIX/unaligned/2/array_tests.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="array_tests.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="array_tests.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/libraries/System.Data.Common/tests/System/Data/Common/DbConnectionStringBuilderTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // Copyright (C) 2008 Daniel Morgan // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #region Using directives using System.Collections; using System.Collections.Generic; using System.Data.Common; using System.Text; using System.Text.RegularExpressions; using Xunit; #endregion namespace System.Data.Tests.Common { public class DbConnectionStringBuilderTest { private DbConnectionStringBuilder _builder = null; private const string SERVER = "SERVER"; private const string SERVER_VALUE = "localhost"; public DbConnectionStringBuilderTest() { _builder = new DbConnectionStringBuilder(); } [Fact] public void Add() { _builder.Add("driverid", "420"); _builder.Add("driverid", "560"); _builder.Add("DriverID", "840"); Assert.Equal("840", _builder["driverId"]); Assert.True(_builder.ContainsKey("driverId")); _builder.Add("Driver", "OdbcDriver"); Assert.Equal("OdbcDriver", _builder["Driver"]); Assert.True(_builder.ContainsKey("Driver")); _builder.Add("Driver", "{OdbcDriver"); Assert.Equal("{OdbcDriver", _builder["Driver"]); Assert.True(_builder.ContainsKey("Driver")); _builder.Add("Dsn", "MyDsn"); Assert.Equal("MyDsn", _builder["Dsn"]); Assert.True(_builder.ContainsKey("Dsn")); _builder.Add("dsN", "MyDsn2"); Assert.Equal("MyDsn2", _builder["Dsn"]); Assert.True(_builder.ContainsKey("Dsn")); } [Fact] public void Add_Keyword_Invalid() { string[] invalid_keywords = new string[] { string.Empty, " ", " abc", "abc ", "\r", "ab\rc", ";abc", "a\0b" }; for (int i = 0; i < invalid_keywords.Length; i++) { string keyword = invalid_keywords[i]; ArgumentException ex = Assert.Throws<ArgumentException>(() => _builder.Add(keyword, "abc")); // Invalid keyword, contain one or more of 'no characters', // 'control characters', 'leading or trailing whitespace' // or 'leading semicolons' Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Contains(keyword, ex.Message); Assert.Equal(keyword, ex.ParamName); } } [Fact] public void Add_Keyword_Null() { ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() => _builder.Add(null, "abc")); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Equal("keyword", ex.ParamName); } [Fact] public void ConnectionString() { DbConnectionStringBuilder sb; sb = new DbConnectionStringBuilder(); sb.ConnectionString = "A=B"; Assert.True(sb.ContainsKey("A")); Assert.Equal("a=B", sb.ConnectionString); Assert.Equal(1, sb.Count); Assert.Equal(1, sb.Keys.Count); sb.ConnectionString = null; Assert.False(sb.ContainsKey("A")); Assert.Equal(string.Empty, sb.ConnectionString); Assert.Equal(0, sb.Count); Assert.Equal(0, sb.Keys.Count); sb = new DbConnectionStringBuilder(); sb.ConnectionString = "A=B"; sb.ConnectionString = string.Empty; Assert.False(sb.ContainsKey("A")); Assert.Equal(string.Empty, sb.ConnectionString); Assert.Equal(0, sb.Count); Assert.Equal(0, sb.Keys.Count); sb = new DbConnectionStringBuilder(); sb.ConnectionString = "A=B"; sb.ConnectionString = "\r "; Assert.False(sb.ContainsKey("A")); Assert.Equal(string.Empty, sb.ConnectionString); Assert.Equal(0, sb.Count); Assert.Equal(0, sb.Keys.Count); } [Fact] public void ConnectionString_Value_Empty() { DbConnectionStringBuilder[] sbs = new DbConnectionStringBuilder[] { new DbConnectionStringBuilder (), new DbConnectionStringBuilder (false), new DbConnectionStringBuilder (true) }; foreach (DbConnectionStringBuilder sb in sbs) { sb.ConnectionString = "A="; Assert.False(sb.ContainsKey("A")); Assert.Equal(string.Empty, sb.ConnectionString); Assert.Equal(0, sb.Count); } } [Fact] public void Clear() { DbConnectionStringBuilder[] sbs = new DbConnectionStringBuilder[] { new DbConnectionStringBuilder (), new DbConnectionStringBuilder (false), new DbConnectionStringBuilder (true) }; foreach (DbConnectionStringBuilder sb in sbs) { sb["Dbq"] = "C:\\Data.xls"; sb["Driver"] = "790"; sb.Add("Port", "56"); sb.Clear(); Assert.Equal(string.Empty, sb.ConnectionString); Assert.False(sb.ContainsKey("Dbq")); Assert.False(sb.ContainsKey("Driver")); Assert.False(sb.ContainsKey("Port")); Assert.Equal(0, sb.Count); Assert.Equal(0, sb.Keys.Count); Assert.Equal(0, sb.Values.Count); } } [Fact] public void AddDuplicateTest() { _builder.Add(SERVER, SERVER_VALUE); _builder.Add(SERVER, SERVER_VALUE); // should allow duplicate addition. rather, it should re-assign Assert.Equal(SERVER + "=" + SERVER_VALUE, _builder.ConnectionString); } [Fact] public void Indexer() { _builder["abc Def"] = "xa 34"; Assert.Equal("xa 34", _builder["abc def"]); Assert.Equal("abc Def=\"xa 34\"", _builder.ConnectionString); _builder["na;"] = "abc;"; Assert.Equal("abc;", _builder["na;"]); Assert.Equal("abc Def=\"xa 34\";na;=\"abc;\"", _builder.ConnectionString); _builder["Na;"] = "de\rfg"; Assert.Equal("de\rfg", _builder["na;"]); Assert.Equal("abc Def=\"xa 34\";na;=\"de\rfg\"", _builder.ConnectionString); _builder["val"] = ";xyz"; Assert.Equal(";xyz", _builder["val"]); Assert.Equal("abc Def=\"xa 34\";na;=\"de\rfg\";val=\";xyz\"", _builder.ConnectionString); _builder["name"] = string.Empty; Assert.Equal(string.Empty, _builder["name"]); Assert.Equal("abc Def=\"xa 34\";na;=\"de\rfg\";val=\";xyz\";name=", _builder.ConnectionString); _builder["name"] = " "; Assert.Equal(" ", _builder["name"]); Assert.Equal("abc Def=\"xa 34\";na;=\"de\rfg\";val=\";xyz\";name=\" \"", _builder.ConnectionString); _builder = new DbConnectionStringBuilder(false); _builder["abc Def"] = "xa 34"; Assert.Equal("xa 34", _builder["abc def"]); Assert.Equal("abc Def=\"xa 34\"", _builder.ConnectionString); _builder["na;"] = "abc;"; Assert.Equal("abc;", _builder["na;"]); Assert.Equal("abc Def=\"xa 34\";na;=\"abc;\"", _builder.ConnectionString); _builder["Na;"] = "de\rfg"; Assert.Equal("de\rfg", _builder["na;"]); Assert.Equal("abc Def=\"xa 34\";na;=\"de\rfg\"", _builder.ConnectionString); _builder["val"] = ";xyz"; Assert.Equal(";xyz", _builder["val"]); Assert.Equal("abc Def=\"xa 34\";na;=\"de\rfg\";val=\";xyz\"", _builder.ConnectionString); _builder["name"] = string.Empty; Assert.Equal(string.Empty, _builder["name"]); Assert.Equal("abc Def=\"xa 34\";na;=\"de\rfg\";val=\";xyz\";name=", _builder.ConnectionString); _builder["name"] = " "; Assert.Equal(" ", _builder["name"]); Assert.Equal("abc Def=\"xa 34\";na;=\"de\rfg\";val=\";xyz\";name=\" \"", _builder.ConnectionString); _builder = new DbConnectionStringBuilder(true); _builder["abc Def"] = "xa 34"; Assert.Equal("xa 34", _builder["abc def"]); Assert.Equal("abc Def=xa 34", _builder.ConnectionString); _builder["na;"] = "abc;"; Assert.Equal("abc;", _builder["na;"]); Assert.Equal("abc Def=xa 34;na;={abc;}", _builder.ConnectionString); _builder["Na;"] = "de\rfg"; Assert.Equal("de\rfg", _builder["na;"]); Assert.Equal("abc Def=xa 34;na;=de\rfg", _builder.ConnectionString); _builder["val"] = ";xyz"; Assert.Equal(";xyz", _builder["val"]); Assert.Equal("abc Def=xa 34;na;=de\rfg;val={;xyz}", _builder.ConnectionString); _builder["name"] = string.Empty; Assert.Equal(string.Empty, _builder["name"]); Assert.Equal("abc Def=xa 34;na;=de\rfg;val={;xyz};name=", _builder.ConnectionString); _builder["name"] = " "; Assert.Equal(" ", _builder["name"]); Assert.Equal("abc Def=xa 34;na;=de\rfg;val={;xyz};name= ", _builder.ConnectionString); } [Fact] public void Indexer_Keyword_Invalid() { string[] invalid_keywords = new string[] { string.Empty, " ", " abc", "abc ", "\r", "ab\rc", ";abc", "a\0b" }; for (int i = 0; i < invalid_keywords.Length; i++) { string keyword = invalid_keywords[i]; ArgumentException ex = Assert.Throws<ArgumentException>(() => _builder[keyword] = "abc"); // Invalid keyword, contain one or more of 'no characters', // 'control characters', 'leading or trailing whitespace' // or 'leading semicolons' Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Contains(keyword, ex.Message); Assert.Equal(keyword, ex.ParamName); _builder[keyword] = null; Assert.False(_builder.ContainsKey(keyword)); ArgumentException ex2 = Assert.Throws<ArgumentException>(() => _builder[keyword]); // Keyword not supported: '...' Assert.Null(ex2.InnerException); Assert.NotNull(ex2.Message); // \p{Pi} any kind of opening quote https://www.compart.com/en/unicode/category/Pi // \p{Pf} any kind of closing quote https://www.compart.com/en/unicode/category/Pf // \p{Po} any kind of punctuation character that is not a dash, bracket, quote or connector https://www.compart.com/en/unicode/category/Po Assert.Matches(@"[\p{Pi}\p{Po}]" + Regex.Escape(keyword) + @"[\p{Pf}\p{Po}]", ex2.Message); Assert.Null(ex2.ParamName); } } [Fact] public void Indexer_Keyword_NotSupported() { ArgumentException ex = Assert.Throws<ArgumentException>(() => _builder["abc"]); // Keyword not supported: 'abc' Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); // \p{Pi} any kind of opening quote https://www.compart.com/en/unicode/category/Pi // \p{Pf} any kind of closing quote https://www.compart.com/en/unicode/category/Pf // \p{Po} any kind of punctuation character that is not a dash, bracket, quote or connector https://www.compart.com/en/unicode/category/Po Assert.Matches(@"[\p{Pi}\p{Po}]" + "abc" + @"[\p{Pf}\p{Po}]", ex.Message); Assert.Null(ex.ParamName); } [Fact] public void Indexer_Keyword_Null() { ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() => _builder[null] = "abc"); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Equal("keyword", ex.ParamName); ArgumentNullException ex2 = Assert.Throws<ArgumentNullException>(() => _builder[null] = null); Assert.Null(ex2.InnerException); Assert.NotNull(ex2.Message); Assert.Equal("keyword", ex2.ParamName); ArgumentNullException ex3 = Assert.Throws<ArgumentNullException>(() => _builder[null]); Assert.Null(ex3.InnerException); Assert.NotNull(ex3.Message); Assert.Equal("keyword", ex3.ParamName); } [Fact] public void Indexer_Value_Null() { _builder["DriverID"] = null; Assert.Equal(string.Empty, _builder.ConnectionString); ArgumentException ex = Assert.Throws<ArgumentException>(() => _builder["DriverID"]); // Keyword not supported: 'DriverID' Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); // \p{Pi} any kind of opening quote https://www.compart.com/en/unicode/category/Pi // \p{Pf} any kind of closing quote https://www.compart.com/en/unicode/category/Pf // \p{Po} any kind of punctuation character that is not a dash, bracket, quote or connector https://www.compart.com/en/unicode/category/Po Assert.Matches(@"[\p{Pi}\p{Po}]" + "DriverID" + @"[\p{Pf}\p{Po}]", ex.Message); Assert.Null(ex.ParamName); Assert.False(_builder.ContainsKey("DriverID")); Assert.Equal(string.Empty, _builder.ConnectionString); _builder["DriverID"] = "A"; Assert.Equal("DriverID=A", _builder.ConnectionString); _builder["DriverID"] = null; Assert.False(_builder.ContainsKey("DriverID")); Assert.Equal(string.Empty, _builder.ConnectionString); } [Fact] public void Remove() { Assert.False(_builder.Remove("Dsn")); Assert.False(_builder.Remove("Driver")); _builder.Add("DriverID", "790"); _builder["DefaultDir"] = "C:\\"; Assert.True(_builder.Remove("DriverID")); Assert.False(_builder.ContainsKey("DriverID")); Assert.False(_builder.Remove("DriverID")); Assert.False(_builder.ContainsKey("DriverID")); Assert.True(_builder.Remove("defaulTdIr")); Assert.False(_builder.ContainsKey("DefaultDir")); Assert.False(_builder.Remove("defaulTdIr")); Assert.False(_builder.Remove("userid")); Assert.False(_builder.Remove(string.Empty)); Assert.False(_builder.Remove("\r")); Assert.False(_builder.Remove("a;")); _builder["Dsn"] = "myDsn"; Assert.True(_builder.Remove("Dsn")); Assert.False(_builder.ContainsKey("Dsn")); Assert.False(_builder.Remove("Dsn")); _builder["Driver"] = "SQL Server"; Assert.True(_builder.Remove("Driver")); Assert.False(_builder.ContainsKey("Driver")); Assert.False(_builder.Remove("Driver")); _builder = new DbConnectionStringBuilder(false); Assert.False(_builder.Remove("Dsn")); Assert.False(_builder.Remove("Driver")); _builder.Add("DriverID", "790"); _builder["DefaultDir"] = "C:\\"; Assert.True(_builder.Remove("DriverID")); Assert.False(_builder.ContainsKey("DriverID")); Assert.False(_builder.Remove("DriverID")); Assert.False(_builder.ContainsKey("DriverID")); Assert.True(_builder.Remove("defaulTdIr")); Assert.False(_builder.ContainsKey("DefaultDir")); Assert.False(_builder.Remove("defaulTdIr")); Assert.False(_builder.Remove("userid")); Assert.False(_builder.Remove(string.Empty)); Assert.False(_builder.Remove("\r")); Assert.False(_builder.Remove("a;")); _builder["Dsn"] = "myDsn"; Assert.True(_builder.Remove("Dsn")); Assert.False(_builder.ContainsKey("Dsn")); Assert.False(_builder.Remove("Dsn")); _builder["Driver"] = "SQL Server"; Assert.True(_builder.Remove("Driver")); Assert.False(_builder.ContainsKey("Driver")); Assert.False(_builder.Remove("Driver")); _builder = new DbConnectionStringBuilder(true); Assert.False(_builder.Remove("Dsn")); Assert.False(_builder.Remove("Driver")); _builder.Add("DriverID", "790"); _builder["DefaultDir"] = "C:\\"; Assert.True(_builder.Remove("DriverID")); Assert.False(_builder.ContainsKey("DriverID")); Assert.False(_builder.Remove("DriverID")); Assert.False(_builder.ContainsKey("DriverID")); Assert.True(_builder.Remove("defaulTdIr")); Assert.False(_builder.ContainsKey("DefaultDir")); Assert.False(_builder.Remove("defaulTdIr")); Assert.False(_builder.Remove("userid")); Assert.False(_builder.Remove(string.Empty)); Assert.False(_builder.Remove("\r")); Assert.False(_builder.Remove("a;")); _builder["Dsn"] = "myDsn"; Assert.True(_builder.Remove("Dsn")); Assert.False(_builder.ContainsKey("Dsn")); Assert.False(_builder.Remove("Dsn")); _builder["Driver"] = "SQL Server"; Assert.True(_builder.Remove("Driver")); Assert.False(_builder.ContainsKey("Driver")); Assert.False(_builder.Remove("Driver")); } [Fact] public void Remove_Keyword_Null() { ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() => _builder.Remove(null)); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Equal("keyword", ex.ParamName); } [Fact] public void ContainsKey() { _builder["SourceType"] = "DBC"; _builder.Add("Port", "56"); Assert.True(_builder.ContainsKey("SourceType")); Assert.True(_builder.ContainsKey("Port")); Assert.False(_builder.ContainsKey("Dsn")); Assert.False(_builder.ContainsKey("Driver")); Assert.False(_builder.ContainsKey("xyz")); _builder["Dsn"] = "myDsn"; Assert.True(_builder.ContainsKey("Dsn")); _builder["Driver"] = "SQL Server"; Assert.True(_builder.ContainsKey("Driver")); _builder["abc"] = "pqr"; Assert.True(_builder.ContainsKey("ABC")); Assert.False(_builder.ContainsKey(string.Empty)); _builder = new DbConnectionStringBuilder(false); _builder["SourceType"] = "DBC"; _builder.Add("Port", "56"); Assert.True(_builder.ContainsKey("SourceType")); Assert.True(_builder.ContainsKey("Port")); Assert.False(_builder.ContainsKey("Dsn")); Assert.False(_builder.ContainsKey("Driver")); Assert.False(_builder.ContainsKey("xyz")); _builder["Dsn"] = "myDsn"; Assert.True(_builder.ContainsKey("Dsn")); _builder["Driver"] = "SQL Server"; Assert.True(_builder.ContainsKey("Driver")); _builder["abc"] = "pqr"; Assert.True(_builder.ContainsKey("ABC")); Assert.False(_builder.ContainsKey(string.Empty)); _builder = new DbConnectionStringBuilder(true); _builder["SourceType"] = "DBC"; _builder.Add("Port", "56"); Assert.True(_builder.ContainsKey("SourceType")); Assert.True(_builder.ContainsKey("Port")); Assert.False(_builder.ContainsKey("Dsn")); Assert.False(_builder.ContainsKey("Driver")); Assert.False(_builder.ContainsKey("xyz")); _builder["Dsn"] = "myDsn"; Assert.True(_builder.ContainsKey("Dsn")); _builder["Driver"] = "SQL Server"; Assert.True(_builder.ContainsKey("Driver")); _builder["abc"] = "pqr"; Assert.True(_builder.ContainsKey("ABC")); Assert.False(_builder.ContainsKey(string.Empty)); } [Fact] public void ContainsKey_Keyword_Null() { _builder["SourceType"] = "DBC"; ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() => _builder.ContainsKey(null)); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Equal("keyword", ex.ParamName); } [Fact] public void EquivalentToTest() { _builder.Add(SERVER, SERVER_VALUE); DbConnectionStringBuilder sb2 = new DbConnectionStringBuilder(); sb2.Add(SERVER, SERVER_VALUE); bool value = _builder.EquivalentTo(sb2); Assert.True(value); // negative tests sb2.Add(SERVER + "1", SERVER_VALUE); value = _builder.EquivalentTo(sb2); Assert.False(value); } [Fact] // AppendKeyValuePair (StringBuilder, String, String) public void AppendKeyValuePair1() { StringBuilder sb = new StringBuilder(); DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure"); Assert.Equal("Database=Adventure", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven'ture"); Assert.Equal("Database=\"Adven'ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven\"ture"); Assert.Equal("Database='Adven\"ture'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adventure\""); Assert.Equal("Database='\"Adventure\"'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven'ture\""); Assert.Equal("Database=\"\"\"Adven'ture\"\"\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven;ture"); Assert.Equal("Database=\"Adven;ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure;"); Assert.Equal("Database=\"Adventure;\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", ";Adventure"); Assert.Equal("Database=\";Adventure\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en;ture"); Assert.Equal("Database=\"Adv'en;ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en;ture"); Assert.Equal("Database='Adv\"en;ture'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en;ture"); Assert.Equal("Database=\"A'dv\"\"en;ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven;ture\""); Assert.Equal("Database='\"Adven;ture\"'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven=ture"); Assert.Equal("Database=\"Adven=ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en=ture"); Assert.Equal("Database=\"Adv'en=ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en=ture"); Assert.Equal("Database='Adv\"en=ture'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en=ture"); Assert.Equal("Database=\"A'dv\"\"en=ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven=ture\""); Assert.Equal("Database='\"Adven=ture\"'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven{ture"); Assert.Equal("Database=Adven{ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven}ture"); Assert.Equal("Database=Adven}ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{Adventure"); Assert.Equal("Database={Adventure", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "}Adventure"); Assert.Equal("Database=}Adventure", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure{"); Assert.Equal("Database=Adventure{", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure}"); Assert.Equal("Database=Adventure}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en{ture"); Assert.Equal("Database=\"Adv'en{ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en}ture"); Assert.Equal("Database=\"Adv'en}ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en{ture"); Assert.Equal("Database='Adv\"en{ture'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en}ture"); Assert.Equal("Database='Adv\"en}ture'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en{ture"); Assert.Equal("Database=\"A'dv\"\"en{ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en}ture"); Assert.Equal("Database=\"A'dv\"\"en}ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven{ture\""); Assert.Equal("Database='\"Adven{ture\"'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven}ture\""); Assert.Equal("Database='\"Adven}ture\"'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure"); DbConnectionStringBuilder.AppendKeyValuePair(sb, "Server", "localhost"); Assert.Equal("Database=Adventure;Server=localhost", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", string.Empty); Assert.Equal("Database=", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", null); Assert.Equal("Database=", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Datab=ase", "Adven=ture", false); Assert.Equal("Datab==ase=\"Adven=ture\"", sb.ToString()); } [Fact] // AppendKeyValuePair (StringBuilder, String, String) public void AppendKeyValuePair1_Builder_Null() { ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() => DbConnectionStringBuilder.AppendKeyValuePair(null, "Server", "localhost")); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Equal("builder", ex.ParamName); } [Fact] // AppendKeyValuePair (StringBuilder, String, String) public void AppendKeyValuePair1_Keyword_Empty() { StringBuilder sb = new StringBuilder(); ArgumentException ex = Assert.Throws<ArgumentException>(() => DbConnectionStringBuilder.AppendKeyValuePair(sb, string.Empty, "localhost")); // Expecting non-empty string for 'keyName' parameter Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Null(ex.ParamName); } [Fact] // AppendKeyValuePair (StringBuilder, String, String) public void AppendKeyValuePair1_Keyword_Null() { StringBuilder sb = new StringBuilder(); ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() => DbConnectionStringBuilder.AppendKeyValuePair(sb, null, "localhost")); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Equal("keyName", ex.ParamName); } [Fact] // AppendKeyValuePair (StringBuilder, String, String, Boolean) public void AppendKeyValuePair2_UseOdbcRules_False() { StringBuilder sb = new StringBuilder(); DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure Works", false); Assert.Equal("Database=\"Adventure Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure", false); Assert.Equal("Database=Adventure", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven'ture Works", false); Assert.Equal("Database=\"Adven'ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven'ture", false); Assert.Equal("Database=\"Adven'ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven\"ture Works", false); Assert.Equal("Database='Adven\"ture Works'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven\"ture", false); Assert.Equal("Database='Adven\"ture'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adventure Works\"", false); Assert.Equal("Database='\"Adventure Works\"'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adventure\"", false); Assert.Equal("Database='\"Adventure\"'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven'ture Works\"", false); Assert.Equal("Database=\"\"\"Adven'ture Works\"\"\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven'ture\"", false); Assert.Equal("Database=\"\"\"Adven'ture\"\"\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven;ture Works", false); Assert.Equal("Database=\"Adven;ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven;ture", false); Assert.Equal("Database=\"Adven;ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure Works;", false); Assert.Equal("Database=\"Adventure Works;\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure;", false); Assert.Equal("Database=\"Adventure;\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", ";Adventure Works", false); Assert.Equal("Database=\";Adventure Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", ";Adventure", false); Assert.Equal("Database=\";Adventure\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en;ture Works", false); Assert.Equal("Database=\"Adv'en;ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en;ture", false); Assert.Equal("Database=\"Adv'en;ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en;ture Works", false); Assert.Equal("Database='Adv\"en;ture Works'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en;ture", false); Assert.Equal("Database='Adv\"en;ture'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en;ture Works", false); Assert.Equal("Database=\"A'dv\"\"en;ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en;ture", false); Assert.Equal("Database=\"A'dv\"\"en;ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven;ture Works\"", false); Assert.Equal("Database='\"Adven;ture Works\"'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven;ture\"", false); Assert.Equal("Database='\"Adven;ture\"'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven=ture Works", false); Assert.Equal("Database=\"Adven=ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven=ture", false); Assert.Equal("Database=\"Adven=ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en=ture Works", false); Assert.Equal("Database=\"Adv'en=ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en=ture", false); Assert.Equal("Database=\"Adv'en=ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en=ture Works", false); Assert.Equal("Database='Adv\"en=ture Works'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en=ture", false); Assert.Equal("Database='Adv\"en=ture'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en=ture Works", false); Assert.Equal("Database=\"A'dv\"\"en=ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en=ture", false); Assert.Equal("Database=\"A'dv\"\"en=ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven=ture Works\"", false); Assert.Equal("Database='\"Adven=ture Works\"'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven=ture\"", false); Assert.Equal("Database='\"Adven=ture\"'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven{ture Works", false); Assert.Equal("Database=\"Adven{ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven{ture", false); Assert.Equal("Database=Adven{ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven}ture Works", false); Assert.Equal("Database=\"Adven}ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven}ture", false); Assert.Equal("Database=Adven}ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{Adventure Works", false); Assert.Equal("Database=\"{Adventure Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{Adventure", false); Assert.Equal("Database={Adventure", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "}Adventure Works", false); Assert.Equal("Database=\"}Adventure Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "}Adventure", false); Assert.Equal("Database=}Adventure", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure Works{", false); Assert.Equal("Database=\"Adventure Works{\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure{", false); Assert.Equal("Database=Adventure{", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure Works}", false); Assert.Equal("Database=\"Adventure Works}\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure}", false); Assert.Equal("Database=Adventure}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en{ture Works", false); Assert.Equal("Database=\"Adv'en{ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en{ture", false); Assert.Equal("Database=\"Adv'en{ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en}ture Works", false); Assert.Equal("Database=\"Adv'en}ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en}ture", false); Assert.Equal("Database=\"Adv'en}ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en{ture Works", false); Assert.Equal("Database='Adv\"en{ture Works'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en{ture", false); Assert.Equal("Database='Adv\"en{ture'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en}ture Works", false); Assert.Equal("Database='Adv\"en}ture Works'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en}ture", false); Assert.Equal("Database='Adv\"en}ture'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en{ture Works", false); Assert.Equal("Database=\"A'dv\"\"en{ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en{ture", false); Assert.Equal("Database=\"A'dv\"\"en{ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en}ture Works", false); Assert.Equal("Database=\"A'dv\"\"en}ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en}ture", false); Assert.Equal("Database=\"A'dv\"\"en}ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven{ture Works\"", false); Assert.Equal("Database='\"Adven{ture Works\"'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven{ture\"", false); Assert.Equal("Database='\"Adven{ture\"'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven}ture Works\"", false); Assert.Equal("Database='\"Adven}ture Works\"'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven}ture\"", false); Assert.Equal("Database='\"Adven}ture\"'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{{{B}}}", false); Assert.Equal("Database={{{B}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{{{B}}}", false); Assert.Equal("Driver={{{B}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{A{B{C}D}E}", false); Assert.Equal("Database={A{B{C}D}E}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{A{B{C}D}E}", false); Assert.Equal("Driver={A{B{C}D}E}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{{{B}}", false); Assert.Equal("Database={{{B}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{{{B}}", false); Assert.Equal("Driver={{{B}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{{{B}", false); Assert.Equal("Database={{{B}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{{{B}", false); Assert.Equal("Driver={{{B}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{{B}", false); Assert.Equal("Database={{B}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{{B}", false); Assert.Equal("Driver={{B}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{B}}", false); Assert.Equal("Database={B}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{B}}", false); Assert.Equal("Driver={B}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{B}}C", false); Assert.Equal("Database={B}}C", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{B}}C", false); Assert.Equal("Driver={B}}C", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A{B}}", false); Assert.Equal("Database=A{B}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "A{B}}", false); Assert.Equal("Driver=A{B}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", " {B}} ", false); Assert.Equal("Database=\" {B}} \"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", " {B}} ", false); Assert.Equal("Driver=\" {B}} \"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{{B}}", false); Assert.Equal("Database={{B}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{{B}}", false); Assert.Equal("Driver={{B}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "}}", false); Assert.Equal("Database=}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "}}", false); Assert.Equal("Driver=}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "}", false); Assert.Equal("Database=}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "}", false); Assert.Equal("Driver=}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure Works", false); DbConnectionStringBuilder.AppendKeyValuePair(sb, "Server", "localhost", false); Assert.Equal("Database=\"Adventure Works\";Server=localhost", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure", false); DbConnectionStringBuilder.AppendKeyValuePair(sb, "Server", "localhost", false); Assert.Equal("Database=Adventure;Server=localhost", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", string.Empty, false); Assert.Equal("Database=", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", null, false); Assert.Equal("Database=", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Datab=ase", "Adven=ture", false); Assert.Equal("Datab==ase=\"Adven=ture\"", sb.ToString()); } [Fact] // AppendKeyValuePair (StringBuilder, String, String, Boolean) public void AppendKeyValuePair2_UseOdbcRules_True() { StringBuilder sb = new StringBuilder(); DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure Works", true); Assert.Equal("Database=Adventure Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adventure Works", true); Assert.Equal("Driver={Adventure Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure", true); Assert.Equal("Database=Adventure", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adventure", true); Assert.Equal("Driver={Adventure}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven'ture Works", true); Assert.Equal("Database=Adven'ture Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adven'ture Works", true); Assert.Equal("Driver={Adven'ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven'ture", true); Assert.Equal("Database=Adven'ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adven'ture", true); Assert.Equal("Driver={Adven'ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven\"ture Works", true); Assert.Equal("Database=Adven\"ture Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adven\"ture Works", true); Assert.Equal("Driver={Adven\"ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven\"ture", true); Assert.Equal("Database=Adven\"ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adven\"ture", true); Assert.Equal("Driver={Adven\"ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adventure Works\"", true); Assert.Equal("Database=\"Adventure Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "\"Adventure Works\"", true); Assert.Equal("Driver={\"Adventure Works\"}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adventure\"", true); Assert.Equal("Database=\"Adventure\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "\"Adventure\"", true); Assert.Equal("Driver={\"Adventure\"}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven'ture Works\"", true); Assert.Equal("Database=\"Adven'ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "\"Adven'ture Works\"", true); Assert.Equal("Driver={\"Adven'ture Works\"}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven'ture\"", true); Assert.Equal("Database=\"Adven'ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "\"Adven'ture\"", true); Assert.Equal("Driver={\"Adven'ture\"}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven;ture Works", true); Assert.Equal("Database={Adven;ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adven;ture Works", true); Assert.Equal("Driver={Adven;ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven;ture", true); Assert.Equal("Database={Adven;ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adven;ture", true); Assert.Equal("Driver={Adven;ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure Works;", true); Assert.Equal("Database={Adventure Works;}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adventure Works;", true); Assert.Equal("Driver={Adventure Works;}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure;", true); Assert.Equal("Database={Adventure;}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adventure;", true); Assert.Equal("Driver={Adventure;}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", ";Adventure Works", true); Assert.Equal("Database={;Adventure Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", ";Adventure Works", true); Assert.Equal("Driver={;Adventure Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", ";Adventure", true); Assert.Equal("Database={;Adventure}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", ";Adventure", true); Assert.Equal("Driver={;Adventure}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en;ture Works", true); Assert.Equal("Database={Adv'en;ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv'en;ture Works", true); Assert.Equal("Driver={Adv'en;ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en;ture", true); Assert.Equal("Database={Adv'en;ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv'en;ture", true); Assert.Equal("Driver={Adv'en;ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en;ture Works", true); Assert.Equal("Database={Adv\"en;ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv\"en;ture Works", true); Assert.Equal("Driver={Adv\"en;ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en;ture", true); Assert.Equal("Database={Adv\"en;ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv\"en;ture", true); Assert.Equal("Driver={Adv\"en;ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en;ture Works", true); Assert.Equal("Database={A'dv\"en;ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "A'dv\"en;ture Works", true); Assert.Equal("Driver={A'dv\"en;ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en;ture", true); Assert.Equal("Database={A'dv\"en;ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "A'dv\"en;ture", true); Assert.Equal("Driver={A'dv\"en;ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven;ture Works\"", true); Assert.Equal("Database={\"Adven;ture Works\"}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "\"Adven;ture Works\"", true); Assert.Equal("Driver={\"Adven;ture Works\"}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven;ture\"", true); Assert.Equal("Database={\"Adven;ture\"}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "\"Adven;ture\"", true); Assert.Equal("Driver={\"Adven;ture\"}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven=ture Works", true); Assert.Equal("Database=Adven=ture Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adven=ture Works", true); Assert.Equal("Driver={Adven=ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven=ture", true); Assert.Equal("Database=Adven=ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adven=ture", true); Assert.Equal("Driver={Adven=ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en=ture Works", true); Assert.Equal("Database=Adv'en=ture Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv'en=ture Works", true); Assert.Equal("Driver={Adv'en=ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en=ture", true); Assert.Equal("Database=Adv'en=ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv'en=ture", true); Assert.Equal("Driver={Adv'en=ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en=ture Works", true); Assert.Equal("Database=Adv\"en=ture Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv\"en=ture Works", true); Assert.Equal("Driver={Adv\"en=ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en=ture", true); Assert.Equal("Database=Adv\"en=ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv\"en=ture", true); Assert.Equal("Driver={Adv\"en=ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en=ture Works", true); Assert.Equal("Database=A'dv\"en=ture Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "A'dv\"en=ture Works", true); Assert.Equal("Driver={A'dv\"en=ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en=ture", true); Assert.Equal("Database=A'dv\"en=ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "A'dv\"en=ture", true); Assert.Equal("Driver={A'dv\"en=ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven=ture Works\"", true); Assert.Equal("Database=\"Adven=ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "\"Adven=ture Works\"", true); Assert.Equal("Driver={\"Adven=ture Works\"}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven=ture\"", true); Assert.Equal("Database=\"Adven=ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "\"Adven=ture\"", true); Assert.Equal("Driver={\"Adven=ture\"}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven{ture Works", true); Assert.Equal("Database=Adven{ture Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adven{ture Works", true); Assert.Equal("Driver={Adven{ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven{tu}re Works", true); Assert.Equal("Database=Adven{tu}re Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adven{tu}re Works", true); Assert.Equal("Driver={Adven{tu}}re Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven{ture", true); Assert.Equal("Database=Adven{ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adven{ture", true); Assert.Equal("Driver={Adven{ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven{tu}re", true); Assert.Equal("Database=Adven{tu}re", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adven{tu}re", true); Assert.Equal("Driver={Adven{tu}}re}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven}ture Works", true); Assert.Equal("Database=Adven}ture Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adven}ture Works", true); Assert.Equal("Driver={Adven}}ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven}ture", true); Assert.Equal("Database=Adven}ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adven}ture", true); Assert.Equal("Driver={Adven}}ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{Adventure Works", true); Assert.Equal("Database={{Adventure Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{Adventure Works", true); Assert.Equal("Driver={{Adventure Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{Adventure", true); Assert.Equal("Database={{Adventure}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{Adventure", true); Assert.Equal("Driver={{Adventure}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{Adventure Works}", true); Assert.Equal("Database={Adventure Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{Adventure Works}", true); Assert.Equal("Driver={Adventure Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{Adventu{re Works}", true); Assert.Equal("Database={Adventu{re Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{Adventu{re Works}", true); Assert.Equal("Driver={Adventu{re Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{Adventu}re Works}", true); Assert.Equal("Database={{Adventu}}re Works}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{Adventu}re Works}", true); Assert.Equal("Driver={{Adventu}}re Works}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{Adventure}", true); Assert.Equal("Database={Adventure}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{Adventure}", true); Assert.Equal("Driver={Adventure}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{Adventu{re}", true); Assert.Equal("Database={Adventu{re}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{Adventu{re}", true); Assert.Equal("Driver={Adventu{re}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{Adventu}re}", true); Assert.Equal("Database={{Adventu}}re}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{Adventu}re}", true); Assert.Equal("Driver={{Adventu}}re}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{Adventure }Works", true); Assert.Equal("Database={{Adventure }}Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{Adventure }Works", true); Assert.Equal("Driver={{Adventure }}Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{Adven}ture", true); Assert.Equal("Database={{Adven}}ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{Adven}ture", true); Assert.Equal("Driver={{Adven}}ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "}Adventure Works", true); Assert.Equal("Database=}Adventure Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "}Adventure Works", true); Assert.Equal("Driver={}}Adventure Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "}Adventure", true); Assert.Equal("Database=}Adventure", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "}Adventure", true); Assert.Equal("Driver={}}Adventure}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure Works{", true); Assert.Equal("Database=Adventure Works{", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adventure Works{", true); Assert.Equal("Driver={Adventure Works{}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure{", true); Assert.Equal("Database=Adventure{", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adventure{", true); Assert.Equal("Driver={Adventure{}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure Works}", true); Assert.Equal("Database=Adventure Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adventure Works}", true); Assert.Equal("Driver={Adventure Works}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure}", true); Assert.Equal("Database=Adventure}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adventure}", true); Assert.Equal("Driver={Adventure}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en{ture Works", true); Assert.Equal("Database=Adv'en{ture Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv'en{ture Works", true); Assert.Equal("Driver={Adv'en{ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en{ture", true); Assert.Equal("Database=Adv'en{ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv'en{ture", true); Assert.Equal("Driver={Adv'en{ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en}ture Works", true); Assert.Equal("Database=Adv'en}ture Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv'en}ture Works", true); Assert.Equal("Driver={Adv'en}}ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en}ture", true); Assert.Equal("Database=Adv'en}ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv'en}ture", true); Assert.Equal("Driver={Adv'en}}ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en{ture Works", true); Assert.Equal("Database=Adv\"en{ture Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv\"en{ture Works", true); Assert.Equal("Driver={Adv\"en{ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en{ture", true); Assert.Equal("Database=Adv\"en{ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv\"en{ture", true); Assert.Equal("Driver={Adv\"en{ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en}ture Works", true); Assert.Equal("Database=Adv\"en}ture Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv\"en}ture Works", true); Assert.Equal("Driver={Adv\"en}}ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en}ture", true); Assert.Equal("Database=Adv\"en}ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv\"en}ture", true); Assert.Equal("Driver={Adv\"en}}ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en{ture Works", true); Assert.Equal("Database=A'dv\"en{ture Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "A'dv\"en{ture Works", true); Assert.Equal("Driver={A'dv\"en{ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en{ture", true); Assert.Equal("Database=A'dv\"en{ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "A'dv\"en{ture", true); Assert.Equal("Driver={A'dv\"en{ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en}ture Works", true); Assert.Equal("Database=A'dv\"en}ture Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "A'dv\"en}ture Works", true); Assert.Equal("Driver={A'dv\"en}}ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en}ture", true); Assert.Equal("Database=A'dv\"en}ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "A'dv\"en}ture", true); Assert.Equal("Driver={A'dv\"en}}ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven{ture Works\"", true); Assert.Equal("Database=\"Adven{ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "\"Adven{ture Works\"", true); Assert.Equal("Driver={\"Adven{ture Works\"}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven{ture\"", true); Assert.Equal("Database=\"Adven{ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "\"Adven{ture\"", true); Assert.Equal("Driver={\"Adven{ture\"}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven}ture Works\"", true); Assert.Equal("Database=\"Adven}ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "\"Adven}ture Works\"", true); Assert.Equal("Driver={\"Adven}}ture Works\"}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven}ture\"", true); Assert.Equal("Database=\"Adven}ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "\"Adven}ture\"", true); Assert.Equal("Driver={\"Adven}}ture\"}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{{{B}}}", true); Assert.Equal("Database={{{B}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{{{B}}}", true); Assert.Equal("Driver={{{B}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{A{B{C}D}E}", true); Assert.Equal("Database={{A{B{C}}D}}E}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{A{B{C}D}E}", true); Assert.Equal("Driver={{A{B{C}}D}}E}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{{{B}}", true); Assert.Equal("Database={{{{B}}}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{{{B}}", true); Assert.Equal("Driver={{{{B}}}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{{{B}", true); Assert.Equal("Database={{{B}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{{{B}", true); Assert.Equal("Driver={{{B}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{{B}", true); Assert.Equal("Database={{B}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{{B}", true); Assert.Equal("Driver={{B}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{B}}", true); Assert.Equal("Database={{B}}}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{B}}", true); Assert.Equal("Driver={{B}}}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{B}}C", true); Assert.Equal("Database={{B}}}}C}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{B}}C", true); Assert.Equal("Driver={{B}}}}C}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A{B}}", true); Assert.Equal("Database=A{B}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "A{B}}", true); Assert.Equal("Driver={A{B}}}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", " {B}} ", true); Assert.Equal("Database= {B}} ", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", " {B}} ", true); Assert.Equal("Driver={ {B}}}} }", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{{B}}", true); Assert.Equal("Database={{{B}}}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{{B}}", true); Assert.Equal("Driver={{{B}}}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "}}", true); Assert.Equal("Database=}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "}}", true); Assert.Equal("Driver={}}}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "}", true); Assert.Equal("Database=}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "}", true); Assert.Equal("Driver={}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure Works", true); DbConnectionStringBuilder.AppendKeyValuePair(sb, "Server", "localhost", true); Assert.Equal("Database=Adventure Works;Server=localhost", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adventure Works", true); DbConnectionStringBuilder.AppendKeyValuePair(sb, "Server", "localhost", true); Assert.Equal("Driver={Adventure Works};Server=localhost", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure", true); DbConnectionStringBuilder.AppendKeyValuePair(sb, "Server", "localhost", true); Assert.Equal("Database=Adventure;Server=localhost", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adventure", true); DbConnectionStringBuilder.AppendKeyValuePair(sb, "Server", "localhost", true); Assert.Equal("Driver={Adventure};Server=localhost", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", string.Empty, true); Assert.Equal("Database=", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", string.Empty, true); Assert.Equal("Driver=", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", null, true); Assert.Equal("Database=", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", null, true); Assert.Equal("Driver=", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Datab=ase", "Adven=ture", true); Assert.Equal("Datab=ase=Adven=ture", sb.ToString()); } [Fact] // AppendKeyValuePair (StringBuilder, String, String, Boolean) public void AppendKeyValuePair2_Builder_Null() { ArgumentNullException ex1 = Assert.Throws<ArgumentNullException>(() => DbConnectionStringBuilder.AppendKeyValuePair(null, "Server", "localhost", true)); Assert.Null(ex1.InnerException); Assert.NotNull(ex1.Message); Assert.Equal("builder", ex1.ParamName); ArgumentNullException ex2 = Assert.Throws<ArgumentNullException>(() => DbConnectionStringBuilder.AppendKeyValuePair(null, "Server", "localhost", false)); Assert.Null(ex2.InnerException); Assert.NotNull(ex2.Message); Assert.Equal("builder", ex2.ParamName); } [Fact] // AppendKeyValuePair (StringBuilder, String, String, Boolean) public void AppendKeyValuePair2_Keyword_Empty() { StringBuilder sb = new StringBuilder(); ArgumentException ex1 = Assert.Throws<ArgumentException>(() => DbConnectionStringBuilder.AppendKeyValuePair(sb, string.Empty, "localhost", true)); // Expecting non-empty string for 'keyName' parameter Assert.Null(ex1.InnerException); Assert.NotNull(ex1.Message); Assert.Null(ex1.ParamName); ArgumentException ex2 = Assert.Throws<ArgumentException>(() => DbConnectionStringBuilder.AppendKeyValuePair(sb, string.Empty, "localhost", false)); // Expecting non-empty string for 'keyName' parameter Assert.Null(ex2.InnerException); Assert.NotNull(ex2.Message); Assert.Null(ex2.ParamName); } [Fact] // AppendKeyValuePair (StringBuilder, String, String, Boolean) public void AppendKeyValuePair2_Keyword_Null() { StringBuilder sb = new StringBuilder(); ArgumentNullException ex1 = Assert.Throws<ArgumentNullException>(() => DbConnectionStringBuilder.AppendKeyValuePair(sb, null, "localhost", true)); Assert.Null(ex1.InnerException); Assert.NotNull(ex1.Message); Assert.Equal("keyName", ex1.ParamName); ArgumentNullException ex2 = Assert.Throws<ArgumentNullException>(() => DbConnectionStringBuilder.AppendKeyValuePair(sb, null, "localhost", false)); Assert.Null(ex2.InnerException); Assert.NotNull(ex2.Message); Assert.Equal("keyName", ex2.ParamName); } [Fact] public void ToStringTest() { _builder.Add(SERVER, SERVER_VALUE); string str = _builder.ToString(); string value = _builder.ConnectionString; Assert.Equal(value, str); } [Fact] public void ItemTest() { _builder.Add(SERVER, SERVER_VALUE); string value = (string)_builder[SERVER]; Assert.Equal(SERVER_VALUE, value); } [Fact] public void ICollectionCopyToTest() { KeyValuePair<string, object>[] dict = new KeyValuePair<string, object>[2]; _builder.Add(SERVER, SERVER_VALUE); _builder.Add(SERVER + "1", SERVER_VALUE + "1"); int i = 0; int j = 1; ((ICollection)_builder).CopyTo(dict, 0); Assert.Equal(SERVER, dict[i].Key); Assert.Equal(SERVER_VALUE, dict[i].Value); Assert.Equal(SERVER + "1", dict[j].Key); Assert.Equal(SERVER_VALUE + "1", dict[j].Value); } [Fact] public void NegICollectionCopyToTest() { AssertExtensions.Throws<ArgumentException>(null, () => { KeyValuePair<string, object>[] dict = new KeyValuePair<string, object>[1]; _builder.Add(SERVER, SERVER_VALUE); _builder.Add(SERVER + "1", SERVER_VALUE + "1"); ((ICollection)_builder).CopyTo(dict, 0); Assert.False(true); }); } [Fact] public void TryGetValueTest() { object value = null; _builder["DriverID"] = "790"; _builder.Add("Server", "C:\\"); Assert.True(_builder.TryGetValue("DriverID", out value)); Assert.Equal("790", value); Assert.True(_builder.TryGetValue("SERVER", out value)); Assert.Equal("C:\\", value); Assert.False(_builder.TryGetValue(string.Empty, out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("a;", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("\r", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue(" ", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("doesnotexist", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("Driver", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("Dsn", out value)); Assert.Null(value); _builder = new DbConnectionStringBuilder(false); _builder["DriverID"] = "790"; _builder.Add("Server", "C:\\"); Assert.True(_builder.TryGetValue("DriverID", out value)); Assert.Equal("790", value); Assert.True(_builder.TryGetValue("SERVER", out value)); Assert.Equal("C:\\", value); Assert.False(_builder.TryGetValue(string.Empty, out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("a;", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("\r", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue(" ", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("doesnotexist", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("Driver", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("Dsn", out value)); Assert.Null(value); _builder = new DbConnectionStringBuilder(true); _builder["DriverID"] = "790"; _builder.Add("Server", "C:\\"); Assert.True(_builder.TryGetValue("DriverID", out value)); Assert.Equal("790", value); Assert.True(_builder.TryGetValue("SERVER", out value)); Assert.Equal("C:\\", value); Assert.False(_builder.TryGetValue(string.Empty, out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("a;", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("\r", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue(" ", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("doesnotexist", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("Driver", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("Dsn", out value)); Assert.Null(value); } [Fact] public void TryGetValue_Keyword_Null() { ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() => _builder.TryGetValue(null, out object value)); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Equal("keyword", ex.ParamName); } [Fact] public void EmbeddedCharTest1() { // Notice how the keywords show up in the connection string // in the order they were added. // And notice the case of the keyword when added is preserved // in the connection string. DbConnectionStringBuilder sb = new DbConnectionStringBuilder(); sb["Data Source"] = "testdb"; sb["User ID"] = "someuser"; sb["Password"] = "PLACEHOLDER"; Assert.Equal("Data Source=testdb;User ID=someuser;Password=PLACEHOLDER", sb.ConnectionString); sb["Password"] = "PLACEHOLDER#"; Assert.Equal("Data Source=testdb;User ID=someuser;Password=PLACEHOLDER#", sb.ConnectionString); // an embedded single-quote value will result in the value being delimieted with double quotes sb["Password"] = "PLACEHOLDER\'def"; Assert.Equal("Data Source=testdb;User ID=someuser;Password=\"PLACEHOLDER\'def\"", sb.ConnectionString); // an embedded double-quote value will result in the value being delimieted with single quotes sb["Password"] = "abc\"def"; Assert.Equal("Data Source=testdb;User ID=someuser;Password=\'abc\"def\'", sb.ConnectionString); // an embedded single-quote and double-quote in the value // will result in the value being delimited by double-quotes // with the embedded double quote being escaped with two double-quotes sb["Password"] = "abc\"d\'ef"; Assert.Equal("Data Source=testdb;User ID=someuser;Password=\"abc\"\"d\'ef\"", sb.ConnectionString); sb = new DbConnectionStringBuilder(); sb["PASSWORD"] = "PLACEHOLDERabcdef1"; sb["user id"] = "someuser"; sb["Data Source"] = "testdb"; Assert.Equal("PASSWORD=PLACEHOLDERabcdef1;user id=someuser;Data Source=testdb", sb.ConnectionString); // case is preserved for a keyword that was added the first time sb = new DbConnectionStringBuilder(); sb["PassWord"] = "PLACEHOLDERabcdef2"; sb["uSER iD"] = "someuser"; sb["DaTa SoUrCe"] = "testdb"; Assert.Equal("PassWord=PLACEHOLDERabcdef2;uSER iD=someuser;DaTa SoUrCe=testdb", sb.ConnectionString); sb["passWORD"] = "PLACEHOLDERabc123"; Assert.Equal("PassWord=PLACEHOLDERabc123;uSER iD=someuser;DaTa SoUrCe=testdb", sb.ConnectionString); // embedded equal sign in the value will cause the value to be // delimited with double-quotes sb = new DbConnectionStringBuilder(); sb["Password"] = "PLACEHOLDER=def"; sb["Data Source"] = "testdb"; sb["User ID"] = "someuser"; Assert.Equal("Password=\"PLACEHOLDER=def\";Data Source=testdb;User ID=someuser", sb.ConnectionString); // embedded semicolon in the value will cause the value to be // delimited with double-quotes sb = new DbConnectionStringBuilder(); sb["Password"] = "PLACEHOLDER;def"; sb["Data Source"] = "testdb"; sb["User ID"] = "someuser"; Assert.Equal("Password=\"PLACEHOLDER;def\";Data Source=testdb;User ID=someuser", sb.ConnectionString); // more right parentheses then left parentheses - happily takes it sb = new DbConnectionStringBuilder(); sb.ConnectionString = "Data Source=(((Blah=Something))))))"; Assert.Equal("data source=\"(((Blah=Something))))))\"", sb.ConnectionString); // more left curly braces then right curly braces - happily takes it sb = new DbConnectionStringBuilder(); sb.ConnectionString = "Data Source={{{{Blah=Something}}"; Assert.Equal("data source=\"{{{{Blah=Something}}\"", sb.ConnectionString); // spaces, empty string, null are treated like an empty string // and any previous settings is cleared sb.ConnectionString = " "; Assert.Equal(string.Empty, sb.ConnectionString); sb.ConnectionString = " "; Assert.Equal(string.Empty, sb.ConnectionString); sb.ConnectionString = ""; Assert.Equal(string.Empty, sb.ConnectionString); sb.ConnectionString = string.Empty; Assert.Equal(string.Empty, sb.ConnectionString); sb.ConnectionString = null; Assert.Equal(string.Empty, sb.ConnectionString); sb = new DbConnectionStringBuilder(); Assert.Equal(string.Empty, sb.ConnectionString); } [Fact] public void EmbeddedCharTest2() { DbConnectionStringBuilder sb; sb = new DbConnectionStringBuilder(); sb.ConnectionString = "Driver={SQL Server};Server=(local host);" + "Trusted_Connection=Yes Or No;Database=Adventure Works;"; Assert.Equal("{SQL Server}", sb["Driver"]); Assert.Equal("(local host)", sb["Server"]); Assert.Equal("Yes Or No", sb["Trusted_Connection"]); Assert.Equal("driver=\"{SQL Server}\";server=\"(local host)\";" + "trusted_connection=\"Yes Or No\";database=\"Adventure Works\"", sb.ConnectionString); sb = new DbConnectionStringBuilder(); sb.ConnectionString = "Driver={SQLServer};Server=(local);" + "Trusted_Connection=Yes;Database=AdventureWorks;"; Assert.Equal("{SQLServer}", sb["Driver"]); Assert.Equal("(local)", sb["Server"]); Assert.Equal("Yes", sb["Trusted_Connection"]); Assert.Equal("driver={SQLServer};server=(local);" + "trusted_connection=Yes;database=AdventureWorks", sb.ConnectionString); sb = new DbConnectionStringBuilder(false); sb.ConnectionString = "Driver={SQL Server};Server=(local host);" + "Trusted_Connection=Yes Or No;Database=Adventure Works;"; Assert.Equal("{SQL Server}", sb["Driver"]); Assert.Equal("(local host)", sb["Server"]); Assert.Equal("Yes Or No", sb["Trusted_Connection"]); Assert.Equal("driver=\"{SQL Server}\";server=\"(local host)\";" + "trusted_connection=\"Yes Or No\";database=\"Adventure Works\"", sb.ConnectionString); sb = new DbConnectionStringBuilder(false); sb.ConnectionString = "Driver={SQLServer};Server=(local);" + "Trusted_Connection=Yes;Database=AdventureWorks;"; Assert.Equal("{SQLServer}", sb["Driver"]); Assert.Equal("(local)", sb["Server"]); Assert.Equal("Yes", sb["Trusted_Connection"]); Assert.Equal("driver={SQLServer};server=(local);" + "trusted_connection=Yes;database=AdventureWorks", sb.ConnectionString); sb = new DbConnectionStringBuilder(true); sb.ConnectionString = "Driver={SQL Server};Server=(local host);" + "Trusted_Connection=Yes Or No;Database=Adventure Works;"; Assert.Equal("{SQL Server}", sb["Driver"]); Assert.Equal("(local host)", sb["Server"]); Assert.Equal("Yes Or No", sb["Trusted_Connection"]); Assert.Equal("driver={SQL Server};server=(local host);" + "trusted_connection=Yes Or No;database=Adventure Works", sb.ConnectionString); sb = new DbConnectionStringBuilder(true); sb.ConnectionString = "Driver={SQLServer};Server=(local);" + "Trusted_Connection=Yes;Database=AdventureWorks;"; Assert.Equal("{SQLServer}", sb["Driver"]); Assert.Equal("(local)", sb["Server"]); Assert.Equal("Yes", sb["Trusted_Connection"]); Assert.Equal("driver={SQLServer};server=(local);" + "trusted_connection=Yes;database=AdventureWorks", sb.ConnectionString); } [Fact] public void EmbeddedCharTest3() { string dataSource = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.1.101)" + "(PORT=1521))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=TESTDB)))"; DbConnectionStringBuilder sb; sb = new DbConnectionStringBuilder(); sb.ConnectionString = "User ID=SCOTT;Password=PLACEHOLDER;Data Source=" + dataSource; Assert.Equal(dataSource, sb["Data Source"]); Assert.Equal("SCOTT", sb["User ID"]); Assert.Equal("PLACEHOLDER", sb["Password"]); Assert.Equal( "user id=SCOTT;password=PLACEHOLDER;data source=\"(DESCRIPTION=(ADDRESS=(PROTOCOL=" + "TCP)(HOST=192.168.1.101)(PORT=1521))(CONNECT_DATA=(SERVER=DEDICATED)" + "(SERVICE_NAME=TESTDB)))\"", sb.ConnectionString); sb = new DbConnectionStringBuilder(false); sb.ConnectionString = "User ID=SCOTT;Password=PLACEHOLDER;Data Source=" + dataSource; Assert.Equal(dataSource, sb["Data Source"]); Assert.Equal("SCOTT", sb["User ID"]); Assert.Equal("PLACEHOLDER", sb["Password"]); Assert.Equal( "user id=SCOTT;password=PLACEHOLDER;data source=\"(DESCRIPTION=(ADDRESS=(PROTOCOL=" + "TCP)(HOST=192.168.1.101)(PORT=1521))(CONNECT_DATA=(SERVER=DEDICATED)" + "(SERVICE_NAME=TESTDB)))\"", sb.ConnectionString); sb = new DbConnectionStringBuilder(true); sb.ConnectionString = "User ID=SCOTT;Password=PLACEHOLDER;Data Source=" + dataSource; Assert.Equal(dataSource, sb["Data Source"]); Assert.Equal("SCOTT", sb["User ID"]); Assert.Equal("PLACEHOLDER", sb["Password"]); Assert.Equal( "user id=SCOTT;password=PLACEHOLDER;data source=(DESCRIPTION=(ADDRESS=(PROTOCOL=" + "TCP)(HOST=192.168.1.101)(PORT=1521))(CONNECT_DATA=(SERVER=DEDICATED)" + "(SERVICE_NAME=TESTDB)))", sb.ConnectionString); } [Fact] public void EmbeddedCharTest4() { DbConnectionStringBuilder sb; sb = new DbConnectionStringBuilder(); sb.ConnectionString = "PassWord=PLACEHOLDER;user iD=someuser;DaTa SoUrCe=testdb"; sb["Integrated Security"] = "False"; Assert.Equal( "password=PLACEHOLDER;user id=someuser;data source=testdb;Integrated Security=False", sb.ConnectionString); sb = new DbConnectionStringBuilder(false); sb.ConnectionString = "PassWord=PLACEHOLDER;uSER iD=someuser;DaTa SoUrCe=testdb"; sb["Integrated Security"] = "False"; Assert.Equal( "password=PLACEHOLDER;user id=someuser;data source=testdb;Integrated Security=False", sb.ConnectionString); sb = new DbConnectionStringBuilder(true); sb.ConnectionString = "PassWord=PLACEHOLDER;uSER iD=someuser;DaTa SoUrCe=testdb"; sb["Integrated Security"] = "False"; Assert.Equal( "password=PLACEHOLDER;user id=someuser;data source=testdb;Integrated Security=False", sb.ConnectionString); } [Fact] public void EmbeddedCharTest5() { string connectionString = "A={abcdef2};B=some{us;C=test}db;D=12\"3;E=\"45;6\";F=AB==C;G{A'}\";F={1='\"2};G==C=B==C;Z=ABC"; DbConnectionStringBuilder sb; sb = new DbConnectionStringBuilder(); sb.ConnectionString = connectionString; Assert.Equal("a={abcdef2};b=some{us;c=test}db;d='12\"3';e=\"45;6\";f=\"AB==C\";g{a'}\";f=\"{1='\"\"2}\";g==c=\"B==C\";z=ABC", sb.ConnectionString); Assert.Equal("{abcdef2}", sb["A"]); Assert.Equal("some{us", sb["B"]); Assert.Equal("test}db", sb["C"]); Assert.Equal("12\"3", sb["D"]); Assert.Equal("45;6", sb["E"]); Assert.Equal("AB==C", sb["F"]); Assert.Equal("{1='\"2}", sb["g{a'}\";f"]); Assert.Equal("ABC", sb["Z"]); Assert.Equal("B==C", sb["g=c"]); sb = new DbConnectionStringBuilder(false); sb.ConnectionString = connectionString; Assert.Equal("a={abcdef2};b=some{us;c=test}db;d='12\"3';e=\"45;6\";f=\"AB==C\";g{a'}\";f=\"{1='\"\"2}\";g==c=\"B==C\";z=ABC", sb.ConnectionString); Assert.Equal("{abcdef2}", sb["A"]); Assert.Equal("some{us", sb["B"]); Assert.Equal("test}db", sb["C"]); Assert.Equal("12\"3", sb["D"]); Assert.Equal("45;6", sb["E"]); Assert.Equal("AB==C", sb["F"]); Assert.Equal("{1='\"2}", sb["g{a'}\";f"]); Assert.Equal("ABC", sb["Z"]); Assert.Equal("B==C", sb["g=c"]); sb = new DbConnectionStringBuilder(true); sb.ConnectionString = connectionString; Assert.Equal("a={abcdef2};b=some{us;c=test}db;d=12\"3;e=\"45;6\";f=AB==C;g{a'}\";f={1='\"2};g==C=B==C;z=ABC", sb.ConnectionString); Assert.Equal("{abcdef2}", sb["A"]); Assert.Equal("some{us", sb["B"]); Assert.Equal("test}db", sb["C"]); Assert.Equal("12\"3", sb["D"]); Assert.Equal("\"45", sb["E"]); Assert.Equal("AB==C", sb["6\";f"]); Assert.Equal("{1='\"2}", sb["g{a'}\";f"]); Assert.Equal("ABC", sb["Z"]); Assert.Equal("=C=B==C", sb["g"]); } [Fact] public void EmbeddedCharTest6() { string[][] shared_tests = new string[][] { new string [] { "A=(B;", "A", "(B", "a=(B" }, new string [] { "A={B{}", "A", "{B{}", "a={B{}" }, new string [] { "A={B{{}", "A", "{B{{}", "a={B{{}" }, new string [] { " A =B{C", "A", "B{C", "a=B{C" }, new string [] { " A =B{{C}", "A", "B{{C}", "a=B{{C}" }, new string [] { "A={{{B}}}", "A", "{{{B}}}", "a={{{B}}}" }, new string [] { "A={B}", "A", "{B}", "a={B}" }, new string [] { "A= {B}", "A", "{B}", "a={B}" }, new string [] { " A =BC", "a", "BC", "a=BC" }, new string [] { "\rA\t=BC", "a", "BC", "a=BC" }, new string [] { "\rA\t=BC", "a", "BC", "a=BC" }, new string [] { "A;B=BC", "a;b", "BC", "a;b=BC" }, }; string[][] non_odbc_tests = new string[][] { new string [] { "A=''", "A", "", "a=" }, new string [] { "A='BC;D'", "A", "BC;D", "a=\"BC;D\"" }, new string [] { "A=BC''D", "A", "BC''D", "a=\"BC''D\"" }, new string [] { "A='\"'", "A", "\"", "a='\"'" }, new string [] { "A=B\"\"C;", "A", "B\"\"C", "a='B\"\"C'" }, new string [] { "A={B{", "A", "{B{", "a={B{" }, new string [] { "A={B}C", "A", "{B}C", "a={B}C" }, new string [] { "A=B'C", "A", "B'C", "a=\"B'C\"" }, new string [] { "A=B''C", "A", "B''C", "a=\"B''C\"" }, new string [] { "A= B C ;", "A", "B C", "a=\"B C\"" }, new string [] { "A={B { }} }", "A", "{B { }} }", "a=\"{B { }} }\"" }, new string [] { "A={B {{ }} }", "A", "{B {{ }} }", "a=\"{B {{ }} }\"" }, new string [] { "A= B {C ", "A", "B {C", "a=\"B {C\"" }, new string [] { "A= B }C ", "A", "B }C", "a=\"B }C\"" }, new string [] { "A=B }C", "A", "B }C", "a=\"B }C\"" }, new string [] { "A=B { }C", "A", "B { }C", "a=\"B { }C\"" }, new string [] { "A= B{C {}}", "A", "B{C {}}", "a=\"B{C {}}\"" }, new string [] { "A= {C {};B=A", "A", "{C {}", "a=\"{C {}\";b=A" }, new string [] { "A= {C {} ", "A", "{C {}", "a=\"{C {}\"" }, new string [] { "A= {C {} ;B=A", "A", "{C {}", "a=\"{C {}\";b=A" }, new string [] { "A= {C {}}}", "A", "{C {}}}", "a=\"{C {}}}\"" }, new string [] { "A={B=C}", "A", "{B=C}", "a=\"{B=C}\"" }, new string [] { "A={B==C}", "A", "{B==C}", "a=\"{B==C}\"" }, new string [] { "A=B==C", "A", "B==C", "a=\"B==C\"" }, new string [] { "A={=}", "A", "{=}", "a=\"{=}\"" }, new string [] { "A={==}", "A", "{==}", "a=\"{==}\"" }, new string [] { "A=\"B;(C)'\"", "A", "B;(C)'", "a=\"B;(C)'\"" }, new string [] { "A=B(=)C", "A", "B(=)C", "a=\"B(=)C\"" }, new string [] { "A=B=C", "A", "B=C", "a=\"B=C\"" }, new string [] { "A=B(==)C", "A", "B(==)C", "a=\"B(==)C\"" }, new string [] { "A=B C", "A", "B C", "a=\"B C\"" }, new string [] { "A= B C ", "A", "B C", "a=\"B C\"" }, new string [] { "A= B C ", "A", "B C", "a=\"B C\"" }, new string [] { "A=' B C '", "A", " B C ", "a=\" B C \"" }, new string [] { "A=\" B C \"", "A", " B C ", "a=\" B C \"" }, new string [] { "A={ B C }", "A", "{ B C }", "a=\"{ B C }\"" }, new string [] { "A= B C ;", "A", "B C", "a=\"B C\"" }, new string [] { "A= B\rC\r\t;", "A", "B\rC", "a=\"B\rC\"" }, new string [] { "A=\"\"\"B;C\"\"\"", "A", "\"B;C\"", "a='\"B;C\"'" }, new string [] { "A= \"\"\"B;C\"\"\" ", "A", "\"B;C\"", "a='\"B;C\"'" }, new string [] { "A='''B;C'''", "A", "'B;C'", "a=\"'B;C'\"" }, new string [] { "A= '''B;C''' ", "A", "'B;C'", "a=\"'B;C'\"" }, new string [] { "A={{", "A", "{{", "a={{" }, new string [] { "A={B C}", "A", "{B C}", "a=\"{B C}\"" }, new string [] { "A={ B C }", "A", "{ B C }", "a=\"{ B C }\"" }, new string [] { "A={B {{ } }", "A", "{B {{ } }", "a=\"{B {{ } }\"" }, new string [] { "A='='", "A", "=", "a=\"=\"" }, new string [] { "A='=='", "A", "==", "a=\"==\"" }, new string [] { "A=\"=\"", "A", "=", "a=\"=\"" }, new string [] { "A=\"==\"", "A", "==", "a=\"==\"" }, new string [] { "A={B}}", "A", "{B}}", "a={B}}" }, new string [] { "A=\";\"", "A", ";", "a=\";\"" }, new string [] { "A(=)=B", "A(", ")=B", "a(=\")=B\"" }, new string [] { "A==B=C", "A=B", "C", "a==b=C" }, new string [] { "A===B=C", "A=", "B=C", "a===\"B=C\"" }, new string [] { "(A=)=BC", "(a", ")=BC", "(a=\")=BC\"" }, new string [] { "A==C=B==C", "a=c", "B==C", "a==c=\"B==C\"" }, }; DbConnectionStringBuilder sb; for (int i = 0; i < non_odbc_tests.Length; i++) { string[] test = non_odbc_tests[i]; sb = new DbConnectionStringBuilder(); sb.ConnectionString = test[0]; Assert.Equal(test[3], sb.ConnectionString); Assert.Equal(test[2], sb[test[1]]); } for (int i = 0; i < non_odbc_tests.Length; i++) { string[] test = non_odbc_tests[i]; sb = new DbConnectionStringBuilder(false); sb.ConnectionString = test[0]; Assert.Equal(test[3], sb.ConnectionString); Assert.Equal(test[2], sb[test[1]]); } for (int i = 0; i < shared_tests.Length; i++) { string[] test = shared_tests[i]; sb = new DbConnectionStringBuilder(); sb.ConnectionString = test[0]; Assert.Equal(test[3], sb.ConnectionString); Assert.Equal(test[2], sb[test[1]]); } for (int i = 0; i < shared_tests.Length; i++) { string[] test = shared_tests[i]; sb = new DbConnectionStringBuilder(false); sb.ConnectionString = test[0]; Assert.Equal(test[3], sb.ConnectionString); Assert.Equal(test[2], sb[test[1]]); } string[][] odbc_tests = new string[][] { new string [] { "A=B(=)C", "A", "B(=)C", "a=B(=)C" }, new string [] { "A=B(==)C", "A", "B(==)C", "a=B(==)C" }, new string [] { "A= B C ;", "A", "B C", "a=B C" }, new string [] { "A= B\rC\r\t;", "A", "B\rC", "a=B\rC" }, new string [] { "A='''", "A", "'''", "a='''" }, new string [] { "A=''", "A", "''", "a=''" }, new string [] { "A=''B", "A", "''B", "a=''B" }, new string [] { "A=BC''D", "A", "BC''D", "a=BC''D" }, new string [] { "A='\"'", "A", "'\"'", "a='\"'" }, new string [] { "A=\"\"B", "A", "\"\"B", "a=\"\"B"}, new string [] { "A=B\"\"C;", "A", "B\"\"C", "a=B\"\"C" }, new string [] { "A=\"B", "A", "\"B", "a=\"B" }, new string [] { "A=\"", "A", "\"", "a=\"" }, new string [] { "A=B'C", "A", "B'C", "a=B'C" }, new string [] { "A=B''C", "A", "B''C", "a=B''C" }, new string [] { "A='A'C", "A", "'A'C", "a='A'C" }, new string [] { "A=B C", "A", "B C", "a=B C" }, new string [] { "A= B C ", "A", "B C", "a=B C" }, new string [] { "A= B C ", "A", "B C", "a=B C" }, new string [] { "A=' B C '", "A", "' B C '", "a=' B C '" }, new string [] { "A=\" B C \"", "A", "\" B C \"", "a=\" B C \"" }, new string [] { "A={ B C }", "A", "{ B C }", "a={ B C }" }, new string [] { "A= B C ;", "A", "B C", "a=B C" }, new string [] { "A=\"\"BC\"\"", "A", "\"\"BC\"\"", "a=\"\"BC\"\"" }, new string [] { "A=\"\"B\"C\"\";", "A", "\"\"B\"C\"\"", "a=\"\"B\"C\"\"" }, new string [] { "A= \"\"B\"C\"\" ", "A", "\"\"B\"C\"\"", "a=\"\"B\"C\"\"" }, new string [] { "A=''BC''", "A", "''BC''", "a=''BC''" }, new string [] { "A=''B'C'';", "A", "''B'C''", "a=''B'C''" }, new string [] { "A= ''B'C'' ", "A", "''B'C''", "a=''B'C''" }, new string [] { "A={B C}", "A", "{B C}", "a={B C}" }, new string [] { "A={ B C }", "A", "{ B C }", "a={ B C }" }, new string [] { "A={ B;C }", "A", "{ B;C }", "a={ B;C }" }, new string [] { "A={B { }} }", "A", "{B { }} }", "a={B { }} }" }, new string [] { "A={ B;= {;=}};= }", "A", "{ B;= {;=}};= }", "a={ B;= {;=}};= }" }, new string [] { "A={B {{ }} }", "A", "{B {{ }} }", "a={B {{ }} }" }, new string [] { "A={ B;= {{:= }};= }", "A", "{ B;= {{:= }};= }", "a={ B;= {{:= }};= }" }, new string [] { "A= B {C ", "A", "B {C", "a=B {C" }, new string [] { "A= B }C ", "A", "B }C", "a=B }C" }, new string [] { "A=B }C", "A", "B }C", "a=B }C" }, new string [] { "A=B { }C", "A", "B { }C", "a=B { }C" }, new string [] { "A= {B;{}", "A", "{B;{}", "a={B;{}" }, new string [] { "A= {B;{}}}", "A", "{B;{}}}", "a={B;{}}}" }, new string [] { "A= B{C {}}", "A", "B{C {}}", "a=B{C {}}" }, new string [] { "A= {C {};B=A", "A", "{C {}", "a={C {};b=A" }, new string [] { "A= {C {} ", "A", "{C {}", "a={C {}" }, new string [] { "A= {C {} ;B=A", "A", "{C {}", "a={C {};b=A" }, new string [] { "A= {C {}}}", "A", "{C {}}}", "a={C {}}}" }, new string [] { "A={B=C}", "A", "{B=C}", "a={B=C}" }, new string [] { "A={B==C}", "A", "{B==C}", "a={B==C}" }, new string [] { "A=B==C", "A", "B==C", "a=B==C" }, new string [] { "A='='", "A", "'='", "a='='" }, new string [] { "A='=='", "A", "'=='", "a='=='" }, new string [] { "A=\"=\"", "A", "\"=\"", "a=\"=\"" }, new string [] { "A=\"==\"", "A", "\"==\"", "a=\"==\"" }, new string [] { "A={=}", "A", "{=}", "a={=}" }, new string [] { "A={==}", "A", "{==}", "a={==}" }, new string [] { "A=B=C", "A", "B=C", "a=B=C" }, new string [] { "A(=)=B", "A(", ")=B", "a(=)=B" }, new string [] { "A==B=C", "A", "=B=C", "a==B=C" }, new string [] { "A===B=C", "A", "==B=C", "a===B=C" }, new string [] { "A'='=B=C", "A'", "'=B=C", "a'='=B=C" }, new string [] { "A\"=\"=B=C", "A\"", "\"=B=C", "a\"=\"=B=C" }, new string [] { "\"A=\"=BC", "\"a", "\"=BC", "\"a=\"=BC" }, new string [] { "(A=)=BC", "(a", ")=BC", "(a=)=BC" }, new string [] { "A==C=B==C", "A", "=C=B==C", "a==C=B==C" }, }; for (int i = 0; i < odbc_tests.Length; i++) { string[] test = odbc_tests[i]; sb = new DbConnectionStringBuilder(true); sb.ConnectionString = test[0]; Assert.Equal(test[3], sb.ConnectionString); Assert.Equal(test[2], sb[test[1]]); } for (int i = 0; i < shared_tests.Length; i++) { string[] test = shared_tests[i]; sb = new DbConnectionStringBuilder(true); sb.ConnectionString = test[0]; Assert.Equal(test[3], sb.ConnectionString); Assert.Equal(test[2], sb[test[1]]); } // each test that is in odbc_tests and not in non_odbc_tests // (or vice versa) should result in an ArgumentException AssertValueTest(non_odbc_tests, odbc_tests, true); AssertValueTest(odbc_tests, non_odbc_tests, false); } [Fact] public void EmbeddedChar_ConnectionString_Invalid() { string[] tests = new string[] { " =", "=", "=;", "=ABC;", "='A'", "A", "A=(B;)", "A=B';'C", "A=B { {;} }", "A=B { ; }C", "A=BC'E;F'D", }; DbConnectionStringBuilder[] cbs = new DbConnectionStringBuilder[] { new DbConnectionStringBuilder (), new DbConnectionStringBuilder (false), new DbConnectionStringBuilder (true) }; for (int i = 0; i < tests.Length; i++) { for (int j = 0; j < cbs.Length; j++) { DbConnectionStringBuilder cb = cbs[j]; try { cb.ConnectionString = tests[i]; Assert.False(true); } catch (ArgumentException ex) { // Format of the initialization string does // not conform to specification starting // at index 0 Assert.Equal(typeof(ArgumentException), ex.GetType()); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Null(ex.ParamName); } } } } private void AssertValueTest(string[][] tests1, string[][] tests2, bool useOdbc) { DbConnectionStringBuilder sb = new DbConnectionStringBuilder(useOdbc); for (int i = 0; i < tests1.Length; i++) { string[] test1 = tests1[i]; bool found = false; for (int j = 0; j < tests2.Length; j++) { string[] test2 = tests2[j]; if (test2[0] == test1[0]) { found = true; if (test2[1] != test1[1]) continue; if (test2[2] != test1[2]) continue; if (test2[3] != test1[3]) continue; Assert.False(true); } } if (found) continue; ArgumentException ex = Assert.Throws<ArgumentException>(() => sb.ConnectionString = test1[0]); // Format of the initialization string does // not conform to specification starting // at index 0 Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Null(ex.ParamName); } // check uniqueness of tests for (int i = 0; i < tests1.Length; i++) { for (int j = 0; j < tests1.Length; j++) { if (i == j) continue; Assert.NotEqual(tests1[i], tests1[j]); } } // check uniqueness of tests for (int i = 0; i < tests2.Length; i++) { for (int j = 0; j < tests2.Length; j++) { if (i == j) continue; Assert.NotEqual(tests2[i], tests2[j]); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // Copyright (C) 2008 Daniel Morgan // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #region Using directives using System.Collections; using System.Collections.Generic; using System.Data.Common; using System.Text; using System.Text.RegularExpressions; using Xunit; #endregion namespace System.Data.Tests.Common { public class DbConnectionStringBuilderTest { private DbConnectionStringBuilder _builder = null; private const string SERVER = "SERVER"; private const string SERVER_VALUE = "localhost"; public DbConnectionStringBuilderTest() { _builder = new DbConnectionStringBuilder(); } [Fact] public void Add() { _builder.Add("driverid", "420"); _builder.Add("driverid", "560"); _builder.Add("DriverID", "840"); Assert.Equal("840", _builder["driverId"]); Assert.True(_builder.ContainsKey("driverId")); _builder.Add("Driver", "OdbcDriver"); Assert.Equal("OdbcDriver", _builder["Driver"]); Assert.True(_builder.ContainsKey("Driver")); _builder.Add("Driver", "{OdbcDriver"); Assert.Equal("{OdbcDriver", _builder["Driver"]); Assert.True(_builder.ContainsKey("Driver")); _builder.Add("Dsn", "MyDsn"); Assert.Equal("MyDsn", _builder["Dsn"]); Assert.True(_builder.ContainsKey("Dsn")); _builder.Add("dsN", "MyDsn2"); Assert.Equal("MyDsn2", _builder["Dsn"]); Assert.True(_builder.ContainsKey("Dsn")); } [Fact] public void Add_Keyword_Invalid() { string[] invalid_keywords = new string[] { string.Empty, " ", " abc", "abc ", "\r", "ab\rc", ";abc", "a\0b" }; for (int i = 0; i < invalid_keywords.Length; i++) { string keyword = invalid_keywords[i]; ArgumentException ex = Assert.Throws<ArgumentException>(() => _builder.Add(keyword, "abc")); // Invalid keyword, contain one or more of 'no characters', // 'control characters', 'leading or trailing whitespace' // or 'leading semicolons' Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Contains(keyword, ex.Message); Assert.Equal(keyword, ex.ParamName); } } [Fact] public void Add_Keyword_Null() { ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() => _builder.Add(null, "abc")); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Equal("keyword", ex.ParamName); } [Fact] public void ConnectionString() { DbConnectionStringBuilder sb; sb = new DbConnectionStringBuilder(); sb.ConnectionString = "A=B"; Assert.True(sb.ContainsKey("A")); Assert.Equal("a=B", sb.ConnectionString); Assert.Equal(1, sb.Count); Assert.Equal(1, sb.Keys.Count); sb.ConnectionString = null; Assert.False(sb.ContainsKey("A")); Assert.Equal(string.Empty, sb.ConnectionString); Assert.Equal(0, sb.Count); Assert.Equal(0, sb.Keys.Count); sb = new DbConnectionStringBuilder(); sb.ConnectionString = "A=B"; sb.ConnectionString = string.Empty; Assert.False(sb.ContainsKey("A")); Assert.Equal(string.Empty, sb.ConnectionString); Assert.Equal(0, sb.Count); Assert.Equal(0, sb.Keys.Count); sb = new DbConnectionStringBuilder(); sb.ConnectionString = "A=B"; sb.ConnectionString = "\r "; Assert.False(sb.ContainsKey("A")); Assert.Equal(string.Empty, sb.ConnectionString); Assert.Equal(0, sb.Count); Assert.Equal(0, sb.Keys.Count); } [Fact] public void ConnectionString_Value_Empty() { DbConnectionStringBuilder[] sbs = new DbConnectionStringBuilder[] { new DbConnectionStringBuilder (), new DbConnectionStringBuilder (false), new DbConnectionStringBuilder (true) }; foreach (DbConnectionStringBuilder sb in sbs) { sb.ConnectionString = "A="; Assert.False(sb.ContainsKey("A")); Assert.Equal(string.Empty, sb.ConnectionString); Assert.Equal(0, sb.Count); } } [Fact] public void Clear() { DbConnectionStringBuilder[] sbs = new DbConnectionStringBuilder[] { new DbConnectionStringBuilder (), new DbConnectionStringBuilder (false), new DbConnectionStringBuilder (true) }; foreach (DbConnectionStringBuilder sb in sbs) { sb["Dbq"] = "C:\\Data.xls"; sb["Driver"] = "790"; sb.Add("Port", "56"); sb.Clear(); Assert.Equal(string.Empty, sb.ConnectionString); Assert.False(sb.ContainsKey("Dbq")); Assert.False(sb.ContainsKey("Driver")); Assert.False(sb.ContainsKey("Port")); Assert.Equal(0, sb.Count); Assert.Equal(0, sb.Keys.Count); Assert.Equal(0, sb.Values.Count); } } [Fact] public void AddDuplicateTest() { _builder.Add(SERVER, SERVER_VALUE); _builder.Add(SERVER, SERVER_VALUE); // should allow duplicate addition. rather, it should re-assign Assert.Equal(SERVER + "=" + SERVER_VALUE, _builder.ConnectionString); } [Fact] public void Indexer() { _builder["abc Def"] = "xa 34"; Assert.Equal("xa 34", _builder["abc def"]); Assert.Equal("abc Def=\"xa 34\"", _builder.ConnectionString); _builder["na;"] = "abc;"; Assert.Equal("abc;", _builder["na;"]); Assert.Equal("abc Def=\"xa 34\";na;=\"abc;\"", _builder.ConnectionString); _builder["Na;"] = "de\rfg"; Assert.Equal("de\rfg", _builder["na;"]); Assert.Equal("abc Def=\"xa 34\";na;=\"de\rfg\"", _builder.ConnectionString); _builder["val"] = ";xyz"; Assert.Equal(";xyz", _builder["val"]); Assert.Equal("abc Def=\"xa 34\";na;=\"de\rfg\";val=\";xyz\"", _builder.ConnectionString); _builder["name"] = string.Empty; Assert.Equal(string.Empty, _builder["name"]); Assert.Equal("abc Def=\"xa 34\";na;=\"de\rfg\";val=\";xyz\";name=", _builder.ConnectionString); _builder["name"] = " "; Assert.Equal(" ", _builder["name"]); Assert.Equal("abc Def=\"xa 34\";na;=\"de\rfg\";val=\";xyz\";name=\" \"", _builder.ConnectionString); _builder = new DbConnectionStringBuilder(false); _builder["abc Def"] = "xa 34"; Assert.Equal("xa 34", _builder["abc def"]); Assert.Equal("abc Def=\"xa 34\"", _builder.ConnectionString); _builder["na;"] = "abc;"; Assert.Equal("abc;", _builder["na;"]); Assert.Equal("abc Def=\"xa 34\";na;=\"abc;\"", _builder.ConnectionString); _builder["Na;"] = "de\rfg"; Assert.Equal("de\rfg", _builder["na;"]); Assert.Equal("abc Def=\"xa 34\";na;=\"de\rfg\"", _builder.ConnectionString); _builder["val"] = ";xyz"; Assert.Equal(";xyz", _builder["val"]); Assert.Equal("abc Def=\"xa 34\";na;=\"de\rfg\";val=\";xyz\"", _builder.ConnectionString); _builder["name"] = string.Empty; Assert.Equal(string.Empty, _builder["name"]); Assert.Equal("abc Def=\"xa 34\";na;=\"de\rfg\";val=\";xyz\";name=", _builder.ConnectionString); _builder["name"] = " "; Assert.Equal(" ", _builder["name"]); Assert.Equal("abc Def=\"xa 34\";na;=\"de\rfg\";val=\";xyz\";name=\" \"", _builder.ConnectionString); _builder = new DbConnectionStringBuilder(true); _builder["abc Def"] = "xa 34"; Assert.Equal("xa 34", _builder["abc def"]); Assert.Equal("abc Def=xa 34", _builder.ConnectionString); _builder["na;"] = "abc;"; Assert.Equal("abc;", _builder["na;"]); Assert.Equal("abc Def=xa 34;na;={abc;}", _builder.ConnectionString); _builder["Na;"] = "de\rfg"; Assert.Equal("de\rfg", _builder["na;"]); Assert.Equal("abc Def=xa 34;na;=de\rfg", _builder.ConnectionString); _builder["val"] = ";xyz"; Assert.Equal(";xyz", _builder["val"]); Assert.Equal("abc Def=xa 34;na;=de\rfg;val={;xyz}", _builder.ConnectionString); _builder["name"] = string.Empty; Assert.Equal(string.Empty, _builder["name"]); Assert.Equal("abc Def=xa 34;na;=de\rfg;val={;xyz};name=", _builder.ConnectionString); _builder["name"] = " "; Assert.Equal(" ", _builder["name"]); Assert.Equal("abc Def=xa 34;na;=de\rfg;val={;xyz};name= ", _builder.ConnectionString); } [Fact] public void Indexer_Keyword_Invalid() { string[] invalid_keywords = new string[] { string.Empty, " ", " abc", "abc ", "\r", "ab\rc", ";abc", "a\0b" }; for (int i = 0; i < invalid_keywords.Length; i++) { string keyword = invalid_keywords[i]; ArgumentException ex = Assert.Throws<ArgumentException>(() => _builder[keyword] = "abc"); // Invalid keyword, contain one or more of 'no characters', // 'control characters', 'leading or trailing whitespace' // or 'leading semicolons' Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Contains(keyword, ex.Message); Assert.Equal(keyword, ex.ParamName); _builder[keyword] = null; Assert.False(_builder.ContainsKey(keyword)); ArgumentException ex2 = Assert.Throws<ArgumentException>(() => _builder[keyword]); // Keyword not supported: '...' Assert.Null(ex2.InnerException); Assert.NotNull(ex2.Message); // \p{Pi} any kind of opening quote https://www.compart.com/en/unicode/category/Pi // \p{Pf} any kind of closing quote https://www.compart.com/en/unicode/category/Pf // \p{Po} any kind of punctuation character that is not a dash, bracket, quote or connector https://www.compart.com/en/unicode/category/Po Assert.Matches(@"[\p{Pi}\p{Po}]" + Regex.Escape(keyword) + @"[\p{Pf}\p{Po}]", ex2.Message); Assert.Null(ex2.ParamName); } } [Fact] public void Indexer_Keyword_NotSupported() { ArgumentException ex = Assert.Throws<ArgumentException>(() => _builder["abc"]); // Keyword not supported: 'abc' Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); // \p{Pi} any kind of opening quote https://www.compart.com/en/unicode/category/Pi // \p{Pf} any kind of closing quote https://www.compart.com/en/unicode/category/Pf // \p{Po} any kind of punctuation character that is not a dash, bracket, quote or connector https://www.compart.com/en/unicode/category/Po Assert.Matches(@"[\p{Pi}\p{Po}]" + "abc" + @"[\p{Pf}\p{Po}]", ex.Message); Assert.Null(ex.ParamName); } [Fact] public void Indexer_Keyword_Null() { ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() => _builder[null] = "abc"); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Equal("keyword", ex.ParamName); ArgumentNullException ex2 = Assert.Throws<ArgumentNullException>(() => _builder[null] = null); Assert.Null(ex2.InnerException); Assert.NotNull(ex2.Message); Assert.Equal("keyword", ex2.ParamName); ArgumentNullException ex3 = Assert.Throws<ArgumentNullException>(() => _builder[null]); Assert.Null(ex3.InnerException); Assert.NotNull(ex3.Message); Assert.Equal("keyword", ex3.ParamName); } [Fact] public void Indexer_Value_Null() { _builder["DriverID"] = null; Assert.Equal(string.Empty, _builder.ConnectionString); ArgumentException ex = Assert.Throws<ArgumentException>(() => _builder["DriverID"]); // Keyword not supported: 'DriverID' Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); // \p{Pi} any kind of opening quote https://www.compart.com/en/unicode/category/Pi // \p{Pf} any kind of closing quote https://www.compart.com/en/unicode/category/Pf // \p{Po} any kind of punctuation character that is not a dash, bracket, quote or connector https://www.compart.com/en/unicode/category/Po Assert.Matches(@"[\p{Pi}\p{Po}]" + "DriverID" + @"[\p{Pf}\p{Po}]", ex.Message); Assert.Null(ex.ParamName); Assert.False(_builder.ContainsKey("DriverID")); Assert.Equal(string.Empty, _builder.ConnectionString); _builder["DriverID"] = "A"; Assert.Equal("DriverID=A", _builder.ConnectionString); _builder["DriverID"] = null; Assert.False(_builder.ContainsKey("DriverID")); Assert.Equal(string.Empty, _builder.ConnectionString); } [Fact] public void Remove() { Assert.False(_builder.Remove("Dsn")); Assert.False(_builder.Remove("Driver")); _builder.Add("DriverID", "790"); _builder["DefaultDir"] = "C:\\"; Assert.True(_builder.Remove("DriverID")); Assert.False(_builder.ContainsKey("DriverID")); Assert.False(_builder.Remove("DriverID")); Assert.False(_builder.ContainsKey("DriverID")); Assert.True(_builder.Remove("defaulTdIr")); Assert.False(_builder.ContainsKey("DefaultDir")); Assert.False(_builder.Remove("defaulTdIr")); Assert.False(_builder.Remove("userid")); Assert.False(_builder.Remove(string.Empty)); Assert.False(_builder.Remove("\r")); Assert.False(_builder.Remove("a;")); _builder["Dsn"] = "myDsn"; Assert.True(_builder.Remove("Dsn")); Assert.False(_builder.ContainsKey("Dsn")); Assert.False(_builder.Remove("Dsn")); _builder["Driver"] = "SQL Server"; Assert.True(_builder.Remove("Driver")); Assert.False(_builder.ContainsKey("Driver")); Assert.False(_builder.Remove("Driver")); _builder = new DbConnectionStringBuilder(false); Assert.False(_builder.Remove("Dsn")); Assert.False(_builder.Remove("Driver")); _builder.Add("DriverID", "790"); _builder["DefaultDir"] = "C:\\"; Assert.True(_builder.Remove("DriverID")); Assert.False(_builder.ContainsKey("DriverID")); Assert.False(_builder.Remove("DriverID")); Assert.False(_builder.ContainsKey("DriverID")); Assert.True(_builder.Remove("defaulTdIr")); Assert.False(_builder.ContainsKey("DefaultDir")); Assert.False(_builder.Remove("defaulTdIr")); Assert.False(_builder.Remove("userid")); Assert.False(_builder.Remove(string.Empty)); Assert.False(_builder.Remove("\r")); Assert.False(_builder.Remove("a;")); _builder["Dsn"] = "myDsn"; Assert.True(_builder.Remove("Dsn")); Assert.False(_builder.ContainsKey("Dsn")); Assert.False(_builder.Remove("Dsn")); _builder["Driver"] = "SQL Server"; Assert.True(_builder.Remove("Driver")); Assert.False(_builder.ContainsKey("Driver")); Assert.False(_builder.Remove("Driver")); _builder = new DbConnectionStringBuilder(true); Assert.False(_builder.Remove("Dsn")); Assert.False(_builder.Remove("Driver")); _builder.Add("DriverID", "790"); _builder["DefaultDir"] = "C:\\"; Assert.True(_builder.Remove("DriverID")); Assert.False(_builder.ContainsKey("DriverID")); Assert.False(_builder.Remove("DriverID")); Assert.False(_builder.ContainsKey("DriverID")); Assert.True(_builder.Remove("defaulTdIr")); Assert.False(_builder.ContainsKey("DefaultDir")); Assert.False(_builder.Remove("defaulTdIr")); Assert.False(_builder.Remove("userid")); Assert.False(_builder.Remove(string.Empty)); Assert.False(_builder.Remove("\r")); Assert.False(_builder.Remove("a;")); _builder["Dsn"] = "myDsn"; Assert.True(_builder.Remove("Dsn")); Assert.False(_builder.ContainsKey("Dsn")); Assert.False(_builder.Remove("Dsn")); _builder["Driver"] = "SQL Server"; Assert.True(_builder.Remove("Driver")); Assert.False(_builder.ContainsKey("Driver")); Assert.False(_builder.Remove("Driver")); } [Fact] public void Remove_Keyword_Null() { ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() => _builder.Remove(null)); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Equal("keyword", ex.ParamName); } [Fact] public void ContainsKey() { _builder["SourceType"] = "DBC"; _builder.Add("Port", "56"); Assert.True(_builder.ContainsKey("SourceType")); Assert.True(_builder.ContainsKey("Port")); Assert.False(_builder.ContainsKey("Dsn")); Assert.False(_builder.ContainsKey("Driver")); Assert.False(_builder.ContainsKey("xyz")); _builder["Dsn"] = "myDsn"; Assert.True(_builder.ContainsKey("Dsn")); _builder["Driver"] = "SQL Server"; Assert.True(_builder.ContainsKey("Driver")); _builder["abc"] = "pqr"; Assert.True(_builder.ContainsKey("ABC")); Assert.False(_builder.ContainsKey(string.Empty)); _builder = new DbConnectionStringBuilder(false); _builder["SourceType"] = "DBC"; _builder.Add("Port", "56"); Assert.True(_builder.ContainsKey("SourceType")); Assert.True(_builder.ContainsKey("Port")); Assert.False(_builder.ContainsKey("Dsn")); Assert.False(_builder.ContainsKey("Driver")); Assert.False(_builder.ContainsKey("xyz")); _builder["Dsn"] = "myDsn"; Assert.True(_builder.ContainsKey("Dsn")); _builder["Driver"] = "SQL Server"; Assert.True(_builder.ContainsKey("Driver")); _builder["abc"] = "pqr"; Assert.True(_builder.ContainsKey("ABC")); Assert.False(_builder.ContainsKey(string.Empty)); _builder = new DbConnectionStringBuilder(true); _builder["SourceType"] = "DBC"; _builder.Add("Port", "56"); Assert.True(_builder.ContainsKey("SourceType")); Assert.True(_builder.ContainsKey("Port")); Assert.False(_builder.ContainsKey("Dsn")); Assert.False(_builder.ContainsKey("Driver")); Assert.False(_builder.ContainsKey("xyz")); _builder["Dsn"] = "myDsn"; Assert.True(_builder.ContainsKey("Dsn")); _builder["Driver"] = "SQL Server"; Assert.True(_builder.ContainsKey("Driver")); _builder["abc"] = "pqr"; Assert.True(_builder.ContainsKey("ABC")); Assert.False(_builder.ContainsKey(string.Empty)); } [Fact] public void ContainsKey_Keyword_Null() { _builder["SourceType"] = "DBC"; ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() => _builder.ContainsKey(null)); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Equal("keyword", ex.ParamName); } [Fact] public void EquivalentToTest() { _builder.Add(SERVER, SERVER_VALUE); DbConnectionStringBuilder sb2 = new DbConnectionStringBuilder(); sb2.Add(SERVER, SERVER_VALUE); bool value = _builder.EquivalentTo(sb2); Assert.True(value); // negative tests sb2.Add(SERVER + "1", SERVER_VALUE); value = _builder.EquivalentTo(sb2); Assert.False(value); } [Fact] // AppendKeyValuePair (StringBuilder, String, String) public void AppendKeyValuePair1() { StringBuilder sb = new StringBuilder(); DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure"); Assert.Equal("Database=Adventure", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven'ture"); Assert.Equal("Database=\"Adven'ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven\"ture"); Assert.Equal("Database='Adven\"ture'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adventure\""); Assert.Equal("Database='\"Adventure\"'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven'ture\""); Assert.Equal("Database=\"\"\"Adven'ture\"\"\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven;ture"); Assert.Equal("Database=\"Adven;ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure;"); Assert.Equal("Database=\"Adventure;\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", ";Adventure"); Assert.Equal("Database=\";Adventure\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en;ture"); Assert.Equal("Database=\"Adv'en;ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en;ture"); Assert.Equal("Database='Adv\"en;ture'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en;ture"); Assert.Equal("Database=\"A'dv\"\"en;ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven;ture\""); Assert.Equal("Database='\"Adven;ture\"'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven=ture"); Assert.Equal("Database=\"Adven=ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en=ture"); Assert.Equal("Database=\"Adv'en=ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en=ture"); Assert.Equal("Database='Adv\"en=ture'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en=ture"); Assert.Equal("Database=\"A'dv\"\"en=ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven=ture\""); Assert.Equal("Database='\"Adven=ture\"'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven{ture"); Assert.Equal("Database=Adven{ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven}ture"); Assert.Equal("Database=Adven}ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{Adventure"); Assert.Equal("Database={Adventure", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "}Adventure"); Assert.Equal("Database=}Adventure", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure{"); Assert.Equal("Database=Adventure{", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure}"); Assert.Equal("Database=Adventure}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en{ture"); Assert.Equal("Database=\"Adv'en{ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en}ture"); Assert.Equal("Database=\"Adv'en}ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en{ture"); Assert.Equal("Database='Adv\"en{ture'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en}ture"); Assert.Equal("Database='Adv\"en}ture'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en{ture"); Assert.Equal("Database=\"A'dv\"\"en{ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en}ture"); Assert.Equal("Database=\"A'dv\"\"en}ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven{ture\""); Assert.Equal("Database='\"Adven{ture\"'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven}ture\""); Assert.Equal("Database='\"Adven}ture\"'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure"); DbConnectionStringBuilder.AppendKeyValuePair(sb, "Server", "localhost"); Assert.Equal("Database=Adventure;Server=localhost", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", string.Empty); Assert.Equal("Database=", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", null); Assert.Equal("Database=", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Datab=ase", "Adven=ture", false); Assert.Equal("Datab==ase=\"Adven=ture\"", sb.ToString()); } [Fact] // AppendKeyValuePair (StringBuilder, String, String) public void AppendKeyValuePair1_Builder_Null() { ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() => DbConnectionStringBuilder.AppendKeyValuePair(null, "Server", "localhost")); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Equal("builder", ex.ParamName); } [Fact] // AppendKeyValuePair (StringBuilder, String, String) public void AppendKeyValuePair1_Keyword_Empty() { StringBuilder sb = new StringBuilder(); ArgumentException ex = Assert.Throws<ArgumentException>(() => DbConnectionStringBuilder.AppendKeyValuePair(sb, string.Empty, "localhost")); // Expecting non-empty string for 'keyName' parameter Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Null(ex.ParamName); } [Fact] // AppendKeyValuePair (StringBuilder, String, String) public void AppendKeyValuePair1_Keyword_Null() { StringBuilder sb = new StringBuilder(); ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() => DbConnectionStringBuilder.AppendKeyValuePair(sb, null, "localhost")); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Equal("keyName", ex.ParamName); } [Fact] // AppendKeyValuePair (StringBuilder, String, String, Boolean) public void AppendKeyValuePair2_UseOdbcRules_False() { StringBuilder sb = new StringBuilder(); DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure Works", false); Assert.Equal("Database=\"Adventure Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure", false); Assert.Equal("Database=Adventure", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven'ture Works", false); Assert.Equal("Database=\"Adven'ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven'ture", false); Assert.Equal("Database=\"Adven'ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven\"ture Works", false); Assert.Equal("Database='Adven\"ture Works'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven\"ture", false); Assert.Equal("Database='Adven\"ture'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adventure Works\"", false); Assert.Equal("Database='\"Adventure Works\"'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adventure\"", false); Assert.Equal("Database='\"Adventure\"'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven'ture Works\"", false); Assert.Equal("Database=\"\"\"Adven'ture Works\"\"\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven'ture\"", false); Assert.Equal("Database=\"\"\"Adven'ture\"\"\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven;ture Works", false); Assert.Equal("Database=\"Adven;ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven;ture", false); Assert.Equal("Database=\"Adven;ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure Works;", false); Assert.Equal("Database=\"Adventure Works;\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure;", false); Assert.Equal("Database=\"Adventure;\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", ";Adventure Works", false); Assert.Equal("Database=\";Adventure Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", ";Adventure", false); Assert.Equal("Database=\";Adventure\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en;ture Works", false); Assert.Equal("Database=\"Adv'en;ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en;ture", false); Assert.Equal("Database=\"Adv'en;ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en;ture Works", false); Assert.Equal("Database='Adv\"en;ture Works'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en;ture", false); Assert.Equal("Database='Adv\"en;ture'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en;ture Works", false); Assert.Equal("Database=\"A'dv\"\"en;ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en;ture", false); Assert.Equal("Database=\"A'dv\"\"en;ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven;ture Works\"", false); Assert.Equal("Database='\"Adven;ture Works\"'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven;ture\"", false); Assert.Equal("Database='\"Adven;ture\"'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven=ture Works", false); Assert.Equal("Database=\"Adven=ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven=ture", false); Assert.Equal("Database=\"Adven=ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en=ture Works", false); Assert.Equal("Database=\"Adv'en=ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en=ture", false); Assert.Equal("Database=\"Adv'en=ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en=ture Works", false); Assert.Equal("Database='Adv\"en=ture Works'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en=ture", false); Assert.Equal("Database='Adv\"en=ture'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en=ture Works", false); Assert.Equal("Database=\"A'dv\"\"en=ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en=ture", false); Assert.Equal("Database=\"A'dv\"\"en=ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven=ture Works\"", false); Assert.Equal("Database='\"Adven=ture Works\"'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven=ture\"", false); Assert.Equal("Database='\"Adven=ture\"'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven{ture Works", false); Assert.Equal("Database=\"Adven{ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven{ture", false); Assert.Equal("Database=Adven{ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven}ture Works", false); Assert.Equal("Database=\"Adven}ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven}ture", false); Assert.Equal("Database=Adven}ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{Adventure Works", false); Assert.Equal("Database=\"{Adventure Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{Adventure", false); Assert.Equal("Database={Adventure", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "}Adventure Works", false); Assert.Equal("Database=\"}Adventure Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "}Adventure", false); Assert.Equal("Database=}Adventure", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure Works{", false); Assert.Equal("Database=\"Adventure Works{\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure{", false); Assert.Equal("Database=Adventure{", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure Works}", false); Assert.Equal("Database=\"Adventure Works}\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure}", false); Assert.Equal("Database=Adventure}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en{ture Works", false); Assert.Equal("Database=\"Adv'en{ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en{ture", false); Assert.Equal("Database=\"Adv'en{ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en}ture Works", false); Assert.Equal("Database=\"Adv'en}ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en}ture", false); Assert.Equal("Database=\"Adv'en}ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en{ture Works", false); Assert.Equal("Database='Adv\"en{ture Works'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en{ture", false); Assert.Equal("Database='Adv\"en{ture'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en}ture Works", false); Assert.Equal("Database='Adv\"en}ture Works'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en}ture", false); Assert.Equal("Database='Adv\"en}ture'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en{ture Works", false); Assert.Equal("Database=\"A'dv\"\"en{ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en{ture", false); Assert.Equal("Database=\"A'dv\"\"en{ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en}ture Works", false); Assert.Equal("Database=\"A'dv\"\"en}ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en}ture", false); Assert.Equal("Database=\"A'dv\"\"en}ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven{ture Works\"", false); Assert.Equal("Database='\"Adven{ture Works\"'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven{ture\"", false); Assert.Equal("Database='\"Adven{ture\"'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven}ture Works\"", false); Assert.Equal("Database='\"Adven}ture Works\"'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven}ture\"", false); Assert.Equal("Database='\"Adven}ture\"'", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{{{B}}}", false); Assert.Equal("Database={{{B}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{{{B}}}", false); Assert.Equal("Driver={{{B}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{A{B{C}D}E}", false); Assert.Equal("Database={A{B{C}D}E}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{A{B{C}D}E}", false); Assert.Equal("Driver={A{B{C}D}E}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{{{B}}", false); Assert.Equal("Database={{{B}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{{{B}}", false); Assert.Equal("Driver={{{B}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{{{B}", false); Assert.Equal("Database={{{B}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{{{B}", false); Assert.Equal("Driver={{{B}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{{B}", false); Assert.Equal("Database={{B}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{{B}", false); Assert.Equal("Driver={{B}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{B}}", false); Assert.Equal("Database={B}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{B}}", false); Assert.Equal("Driver={B}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{B}}C", false); Assert.Equal("Database={B}}C", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{B}}C", false); Assert.Equal("Driver={B}}C", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A{B}}", false); Assert.Equal("Database=A{B}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "A{B}}", false); Assert.Equal("Driver=A{B}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", " {B}} ", false); Assert.Equal("Database=\" {B}} \"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", " {B}} ", false); Assert.Equal("Driver=\" {B}} \"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{{B}}", false); Assert.Equal("Database={{B}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{{B}}", false); Assert.Equal("Driver={{B}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "}}", false); Assert.Equal("Database=}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "}}", false); Assert.Equal("Driver=}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "}", false); Assert.Equal("Database=}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "}", false); Assert.Equal("Driver=}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure Works", false); DbConnectionStringBuilder.AppendKeyValuePair(sb, "Server", "localhost", false); Assert.Equal("Database=\"Adventure Works\";Server=localhost", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure", false); DbConnectionStringBuilder.AppendKeyValuePair(sb, "Server", "localhost", false); Assert.Equal("Database=Adventure;Server=localhost", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", string.Empty, false); Assert.Equal("Database=", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", null, false); Assert.Equal("Database=", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Datab=ase", "Adven=ture", false); Assert.Equal("Datab==ase=\"Adven=ture\"", sb.ToString()); } [Fact] // AppendKeyValuePair (StringBuilder, String, String, Boolean) public void AppendKeyValuePair2_UseOdbcRules_True() { StringBuilder sb = new StringBuilder(); DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure Works", true); Assert.Equal("Database=Adventure Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adventure Works", true); Assert.Equal("Driver={Adventure Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure", true); Assert.Equal("Database=Adventure", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adventure", true); Assert.Equal("Driver={Adventure}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven'ture Works", true); Assert.Equal("Database=Adven'ture Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adven'ture Works", true); Assert.Equal("Driver={Adven'ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven'ture", true); Assert.Equal("Database=Adven'ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adven'ture", true); Assert.Equal("Driver={Adven'ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven\"ture Works", true); Assert.Equal("Database=Adven\"ture Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adven\"ture Works", true); Assert.Equal("Driver={Adven\"ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven\"ture", true); Assert.Equal("Database=Adven\"ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adven\"ture", true); Assert.Equal("Driver={Adven\"ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adventure Works\"", true); Assert.Equal("Database=\"Adventure Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "\"Adventure Works\"", true); Assert.Equal("Driver={\"Adventure Works\"}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adventure\"", true); Assert.Equal("Database=\"Adventure\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "\"Adventure\"", true); Assert.Equal("Driver={\"Adventure\"}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven'ture Works\"", true); Assert.Equal("Database=\"Adven'ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "\"Adven'ture Works\"", true); Assert.Equal("Driver={\"Adven'ture Works\"}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven'ture\"", true); Assert.Equal("Database=\"Adven'ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "\"Adven'ture\"", true); Assert.Equal("Driver={\"Adven'ture\"}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven;ture Works", true); Assert.Equal("Database={Adven;ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adven;ture Works", true); Assert.Equal("Driver={Adven;ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven;ture", true); Assert.Equal("Database={Adven;ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adven;ture", true); Assert.Equal("Driver={Adven;ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure Works;", true); Assert.Equal("Database={Adventure Works;}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adventure Works;", true); Assert.Equal("Driver={Adventure Works;}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure;", true); Assert.Equal("Database={Adventure;}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adventure;", true); Assert.Equal("Driver={Adventure;}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", ";Adventure Works", true); Assert.Equal("Database={;Adventure Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", ";Adventure Works", true); Assert.Equal("Driver={;Adventure Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", ";Adventure", true); Assert.Equal("Database={;Adventure}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", ";Adventure", true); Assert.Equal("Driver={;Adventure}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en;ture Works", true); Assert.Equal("Database={Adv'en;ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv'en;ture Works", true); Assert.Equal("Driver={Adv'en;ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en;ture", true); Assert.Equal("Database={Adv'en;ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv'en;ture", true); Assert.Equal("Driver={Adv'en;ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en;ture Works", true); Assert.Equal("Database={Adv\"en;ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv\"en;ture Works", true); Assert.Equal("Driver={Adv\"en;ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en;ture", true); Assert.Equal("Database={Adv\"en;ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv\"en;ture", true); Assert.Equal("Driver={Adv\"en;ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en;ture Works", true); Assert.Equal("Database={A'dv\"en;ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "A'dv\"en;ture Works", true); Assert.Equal("Driver={A'dv\"en;ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en;ture", true); Assert.Equal("Database={A'dv\"en;ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "A'dv\"en;ture", true); Assert.Equal("Driver={A'dv\"en;ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven;ture Works\"", true); Assert.Equal("Database={\"Adven;ture Works\"}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "\"Adven;ture Works\"", true); Assert.Equal("Driver={\"Adven;ture Works\"}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven;ture\"", true); Assert.Equal("Database={\"Adven;ture\"}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "\"Adven;ture\"", true); Assert.Equal("Driver={\"Adven;ture\"}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven=ture Works", true); Assert.Equal("Database=Adven=ture Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adven=ture Works", true); Assert.Equal("Driver={Adven=ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven=ture", true); Assert.Equal("Database=Adven=ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adven=ture", true); Assert.Equal("Driver={Adven=ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en=ture Works", true); Assert.Equal("Database=Adv'en=ture Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv'en=ture Works", true); Assert.Equal("Driver={Adv'en=ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en=ture", true); Assert.Equal("Database=Adv'en=ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv'en=ture", true); Assert.Equal("Driver={Adv'en=ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en=ture Works", true); Assert.Equal("Database=Adv\"en=ture Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv\"en=ture Works", true); Assert.Equal("Driver={Adv\"en=ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en=ture", true); Assert.Equal("Database=Adv\"en=ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv\"en=ture", true); Assert.Equal("Driver={Adv\"en=ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en=ture Works", true); Assert.Equal("Database=A'dv\"en=ture Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "A'dv\"en=ture Works", true); Assert.Equal("Driver={A'dv\"en=ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en=ture", true); Assert.Equal("Database=A'dv\"en=ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "A'dv\"en=ture", true); Assert.Equal("Driver={A'dv\"en=ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven=ture Works\"", true); Assert.Equal("Database=\"Adven=ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "\"Adven=ture Works\"", true); Assert.Equal("Driver={\"Adven=ture Works\"}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven=ture\"", true); Assert.Equal("Database=\"Adven=ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "\"Adven=ture\"", true); Assert.Equal("Driver={\"Adven=ture\"}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven{ture Works", true); Assert.Equal("Database=Adven{ture Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adven{ture Works", true); Assert.Equal("Driver={Adven{ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven{tu}re Works", true); Assert.Equal("Database=Adven{tu}re Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adven{tu}re Works", true); Assert.Equal("Driver={Adven{tu}}re Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven{ture", true); Assert.Equal("Database=Adven{ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adven{ture", true); Assert.Equal("Driver={Adven{ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven{tu}re", true); Assert.Equal("Database=Adven{tu}re", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adven{tu}re", true); Assert.Equal("Driver={Adven{tu}}re}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven}ture Works", true); Assert.Equal("Database=Adven}ture Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adven}ture Works", true); Assert.Equal("Driver={Adven}}ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adven}ture", true); Assert.Equal("Database=Adven}ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adven}ture", true); Assert.Equal("Driver={Adven}}ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{Adventure Works", true); Assert.Equal("Database={{Adventure Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{Adventure Works", true); Assert.Equal("Driver={{Adventure Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{Adventure", true); Assert.Equal("Database={{Adventure}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{Adventure", true); Assert.Equal("Driver={{Adventure}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{Adventure Works}", true); Assert.Equal("Database={Adventure Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{Adventure Works}", true); Assert.Equal("Driver={Adventure Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{Adventu{re Works}", true); Assert.Equal("Database={Adventu{re Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{Adventu{re Works}", true); Assert.Equal("Driver={Adventu{re Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{Adventu}re Works}", true); Assert.Equal("Database={{Adventu}}re Works}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{Adventu}re Works}", true); Assert.Equal("Driver={{Adventu}}re Works}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{Adventure}", true); Assert.Equal("Database={Adventure}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{Adventure}", true); Assert.Equal("Driver={Adventure}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{Adventu{re}", true); Assert.Equal("Database={Adventu{re}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{Adventu{re}", true); Assert.Equal("Driver={Adventu{re}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{Adventu}re}", true); Assert.Equal("Database={{Adventu}}re}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{Adventu}re}", true); Assert.Equal("Driver={{Adventu}}re}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{Adventure }Works", true); Assert.Equal("Database={{Adventure }}Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{Adventure }Works", true); Assert.Equal("Driver={{Adventure }}Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{Adven}ture", true); Assert.Equal("Database={{Adven}}ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{Adven}ture", true); Assert.Equal("Driver={{Adven}}ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "}Adventure Works", true); Assert.Equal("Database=}Adventure Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "}Adventure Works", true); Assert.Equal("Driver={}}Adventure Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "}Adventure", true); Assert.Equal("Database=}Adventure", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "}Adventure", true); Assert.Equal("Driver={}}Adventure}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure Works{", true); Assert.Equal("Database=Adventure Works{", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adventure Works{", true); Assert.Equal("Driver={Adventure Works{}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure{", true); Assert.Equal("Database=Adventure{", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adventure{", true); Assert.Equal("Driver={Adventure{}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure Works}", true); Assert.Equal("Database=Adventure Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adventure Works}", true); Assert.Equal("Driver={Adventure Works}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure}", true); Assert.Equal("Database=Adventure}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adventure}", true); Assert.Equal("Driver={Adventure}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en{ture Works", true); Assert.Equal("Database=Adv'en{ture Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv'en{ture Works", true); Assert.Equal("Driver={Adv'en{ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en{ture", true); Assert.Equal("Database=Adv'en{ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv'en{ture", true); Assert.Equal("Driver={Adv'en{ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en}ture Works", true); Assert.Equal("Database=Adv'en}ture Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv'en}ture Works", true); Assert.Equal("Driver={Adv'en}}ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv'en}ture", true); Assert.Equal("Database=Adv'en}ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv'en}ture", true); Assert.Equal("Driver={Adv'en}}ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en{ture Works", true); Assert.Equal("Database=Adv\"en{ture Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv\"en{ture Works", true); Assert.Equal("Driver={Adv\"en{ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en{ture", true); Assert.Equal("Database=Adv\"en{ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv\"en{ture", true); Assert.Equal("Driver={Adv\"en{ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en}ture Works", true); Assert.Equal("Database=Adv\"en}ture Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv\"en}ture Works", true); Assert.Equal("Driver={Adv\"en}}ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adv\"en}ture", true); Assert.Equal("Database=Adv\"en}ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adv\"en}ture", true); Assert.Equal("Driver={Adv\"en}}ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en{ture Works", true); Assert.Equal("Database=A'dv\"en{ture Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "A'dv\"en{ture Works", true); Assert.Equal("Driver={A'dv\"en{ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en{ture", true); Assert.Equal("Database=A'dv\"en{ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "A'dv\"en{ture", true); Assert.Equal("Driver={A'dv\"en{ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en}ture Works", true); Assert.Equal("Database=A'dv\"en}ture Works", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "A'dv\"en}ture Works", true); Assert.Equal("Driver={A'dv\"en}}ture Works}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A'dv\"en}ture", true); Assert.Equal("Database=A'dv\"en}ture", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "A'dv\"en}ture", true); Assert.Equal("Driver={A'dv\"en}}ture}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven{ture Works\"", true); Assert.Equal("Database=\"Adven{ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "\"Adven{ture Works\"", true); Assert.Equal("Driver={\"Adven{ture Works\"}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven{ture\"", true); Assert.Equal("Database=\"Adven{ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "\"Adven{ture\"", true); Assert.Equal("Driver={\"Adven{ture\"}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven}ture Works\"", true); Assert.Equal("Database=\"Adven}ture Works\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "\"Adven}ture Works\"", true); Assert.Equal("Driver={\"Adven}}ture Works\"}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "\"Adven}ture\"", true); Assert.Equal("Database=\"Adven}ture\"", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "\"Adven}ture\"", true); Assert.Equal("Driver={\"Adven}}ture\"}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{{{B}}}", true); Assert.Equal("Database={{{B}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{{{B}}}", true); Assert.Equal("Driver={{{B}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{A{B{C}D}E}", true); Assert.Equal("Database={{A{B{C}}D}}E}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{A{B{C}D}E}", true); Assert.Equal("Driver={{A{B{C}}D}}E}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{{{B}}", true); Assert.Equal("Database={{{{B}}}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{{{B}}", true); Assert.Equal("Driver={{{{B}}}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{{{B}", true); Assert.Equal("Database={{{B}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{{{B}", true); Assert.Equal("Driver={{{B}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{{B}", true); Assert.Equal("Database={{B}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{{B}", true); Assert.Equal("Driver={{B}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{B}}", true); Assert.Equal("Database={{B}}}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{B}}", true); Assert.Equal("Driver={{B}}}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{B}}C", true); Assert.Equal("Database={{B}}}}C}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{B}}C", true); Assert.Equal("Driver={{B}}}}C}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "A{B}}", true); Assert.Equal("Database=A{B}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "A{B}}", true); Assert.Equal("Driver={A{B}}}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", " {B}} ", true); Assert.Equal("Database= {B}} ", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", " {B}} ", true); Assert.Equal("Driver={ {B}}}} }", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "{{B}}", true); Assert.Equal("Database={{{B}}}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "{{B}}", true); Assert.Equal("Driver={{{B}}}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "}}", true); Assert.Equal("Database=}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "}}", true); Assert.Equal("Driver={}}}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "}", true); Assert.Equal("Database=}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "}", true); Assert.Equal("Driver={}}}", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure Works", true); DbConnectionStringBuilder.AppendKeyValuePair(sb, "Server", "localhost", true); Assert.Equal("Database=Adventure Works;Server=localhost", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adventure Works", true); DbConnectionStringBuilder.AppendKeyValuePair(sb, "Server", "localhost", true); Assert.Equal("Driver={Adventure Works};Server=localhost", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", "Adventure", true); DbConnectionStringBuilder.AppendKeyValuePair(sb, "Server", "localhost", true); Assert.Equal("Database=Adventure;Server=localhost", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", "Adventure", true); DbConnectionStringBuilder.AppendKeyValuePair(sb, "Server", "localhost", true); Assert.Equal("Driver={Adventure};Server=localhost", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", string.Empty, true); Assert.Equal("Database=", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", string.Empty, true); Assert.Equal("Driver=", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Database", null, true); Assert.Equal("Database=", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Driver", null, true); Assert.Equal("Driver=", sb.ToString()); sb.Length = 0; DbConnectionStringBuilder.AppendKeyValuePair(sb, "Datab=ase", "Adven=ture", true); Assert.Equal("Datab=ase=Adven=ture", sb.ToString()); } [Fact] // AppendKeyValuePair (StringBuilder, String, String, Boolean) public void AppendKeyValuePair2_Builder_Null() { ArgumentNullException ex1 = Assert.Throws<ArgumentNullException>(() => DbConnectionStringBuilder.AppendKeyValuePair(null, "Server", "localhost", true)); Assert.Null(ex1.InnerException); Assert.NotNull(ex1.Message); Assert.Equal("builder", ex1.ParamName); ArgumentNullException ex2 = Assert.Throws<ArgumentNullException>(() => DbConnectionStringBuilder.AppendKeyValuePair(null, "Server", "localhost", false)); Assert.Null(ex2.InnerException); Assert.NotNull(ex2.Message); Assert.Equal("builder", ex2.ParamName); } [Fact] // AppendKeyValuePair (StringBuilder, String, String, Boolean) public void AppendKeyValuePair2_Keyword_Empty() { StringBuilder sb = new StringBuilder(); ArgumentException ex1 = Assert.Throws<ArgumentException>(() => DbConnectionStringBuilder.AppendKeyValuePair(sb, string.Empty, "localhost", true)); // Expecting non-empty string for 'keyName' parameter Assert.Null(ex1.InnerException); Assert.NotNull(ex1.Message); Assert.Null(ex1.ParamName); ArgumentException ex2 = Assert.Throws<ArgumentException>(() => DbConnectionStringBuilder.AppendKeyValuePair(sb, string.Empty, "localhost", false)); // Expecting non-empty string for 'keyName' parameter Assert.Null(ex2.InnerException); Assert.NotNull(ex2.Message); Assert.Null(ex2.ParamName); } [Fact] // AppendKeyValuePair (StringBuilder, String, String, Boolean) public void AppendKeyValuePair2_Keyword_Null() { StringBuilder sb = new StringBuilder(); ArgumentNullException ex1 = Assert.Throws<ArgumentNullException>(() => DbConnectionStringBuilder.AppendKeyValuePair(sb, null, "localhost", true)); Assert.Null(ex1.InnerException); Assert.NotNull(ex1.Message); Assert.Equal("keyName", ex1.ParamName); ArgumentNullException ex2 = Assert.Throws<ArgumentNullException>(() => DbConnectionStringBuilder.AppendKeyValuePair(sb, null, "localhost", false)); Assert.Null(ex2.InnerException); Assert.NotNull(ex2.Message); Assert.Equal("keyName", ex2.ParamName); } [Fact] public void ToStringTest() { _builder.Add(SERVER, SERVER_VALUE); string str = _builder.ToString(); string value = _builder.ConnectionString; Assert.Equal(value, str); } [Fact] public void ItemTest() { _builder.Add(SERVER, SERVER_VALUE); string value = (string)_builder[SERVER]; Assert.Equal(SERVER_VALUE, value); } [Fact] public void ICollectionCopyToTest() { KeyValuePair<string, object>[] dict = new KeyValuePair<string, object>[2]; _builder.Add(SERVER, SERVER_VALUE); _builder.Add(SERVER + "1", SERVER_VALUE + "1"); int i = 0; int j = 1; ((ICollection)_builder).CopyTo(dict, 0); Assert.Equal(SERVER, dict[i].Key); Assert.Equal(SERVER_VALUE, dict[i].Value); Assert.Equal(SERVER + "1", dict[j].Key); Assert.Equal(SERVER_VALUE + "1", dict[j].Value); } [Fact] public void NegICollectionCopyToTest() { AssertExtensions.Throws<ArgumentException>(null, () => { KeyValuePair<string, object>[] dict = new KeyValuePair<string, object>[1]; _builder.Add(SERVER, SERVER_VALUE); _builder.Add(SERVER + "1", SERVER_VALUE + "1"); ((ICollection)_builder).CopyTo(dict, 0); Assert.False(true); }); } [Fact] public void TryGetValueTest() { object value = null; _builder["DriverID"] = "790"; _builder.Add("Server", "C:\\"); Assert.True(_builder.TryGetValue("DriverID", out value)); Assert.Equal("790", value); Assert.True(_builder.TryGetValue("SERVER", out value)); Assert.Equal("C:\\", value); Assert.False(_builder.TryGetValue(string.Empty, out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("a;", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("\r", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue(" ", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("doesnotexist", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("Driver", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("Dsn", out value)); Assert.Null(value); _builder = new DbConnectionStringBuilder(false); _builder["DriverID"] = "790"; _builder.Add("Server", "C:\\"); Assert.True(_builder.TryGetValue("DriverID", out value)); Assert.Equal("790", value); Assert.True(_builder.TryGetValue("SERVER", out value)); Assert.Equal("C:\\", value); Assert.False(_builder.TryGetValue(string.Empty, out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("a;", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("\r", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue(" ", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("doesnotexist", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("Driver", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("Dsn", out value)); Assert.Null(value); _builder = new DbConnectionStringBuilder(true); _builder["DriverID"] = "790"; _builder.Add("Server", "C:\\"); Assert.True(_builder.TryGetValue("DriverID", out value)); Assert.Equal("790", value); Assert.True(_builder.TryGetValue("SERVER", out value)); Assert.Equal("C:\\", value); Assert.False(_builder.TryGetValue(string.Empty, out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("a;", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("\r", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue(" ", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("doesnotexist", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("Driver", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("Dsn", out value)); Assert.Null(value); } [Fact] public void TryGetValue_Keyword_Null() { ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() => _builder.TryGetValue(null, out object value)); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Equal("keyword", ex.ParamName); } [Fact] public void EmbeddedCharTest1() { // Notice how the keywords show up in the connection string // in the order they were added. // And notice the case of the keyword when added is preserved // in the connection string. DbConnectionStringBuilder sb = new DbConnectionStringBuilder(); sb["Data Source"] = "testdb"; sb["User ID"] = "someuser"; sb["Password"] = "PLACEHOLDER"; Assert.Equal("Data Source=testdb;User ID=someuser;Password=PLACEHOLDER", sb.ConnectionString); sb["Password"] = "PLACEHOLDER#"; Assert.Equal("Data Source=testdb;User ID=someuser;Password=PLACEHOLDER#", sb.ConnectionString); // an embedded single-quote value will result in the value being delimieted with double quotes sb["Password"] = "PLACEHOLDER\'def"; Assert.Equal("Data Source=testdb;User ID=someuser;Password=\"PLACEHOLDER\'def\"", sb.ConnectionString); // an embedded double-quote value will result in the value being delimieted with single quotes sb["Password"] = "abc\"def"; Assert.Equal("Data Source=testdb;User ID=someuser;Password=\'abc\"def\'", sb.ConnectionString); // an embedded single-quote and double-quote in the value // will result in the value being delimited by double-quotes // with the embedded double quote being escaped with two double-quotes sb["Password"] = "abc\"d\'ef"; Assert.Equal("Data Source=testdb;User ID=someuser;Password=\"abc\"\"d\'ef\"", sb.ConnectionString); sb = new DbConnectionStringBuilder(); sb["PASSWORD"] = "PLACEHOLDERabcdef1"; sb["user id"] = "someuser"; sb["Data Source"] = "testdb"; Assert.Equal("PASSWORD=PLACEHOLDERabcdef1;user id=someuser;Data Source=testdb", sb.ConnectionString); // case is preserved for a keyword that was added the first time sb = new DbConnectionStringBuilder(); sb["PassWord"] = "PLACEHOLDERabcdef2"; sb["uSER iD"] = "someuser"; sb["DaTa SoUrCe"] = "testdb"; Assert.Equal("PassWord=PLACEHOLDERabcdef2;uSER iD=someuser;DaTa SoUrCe=testdb", sb.ConnectionString); sb["passWORD"] = "PLACEHOLDERabc123"; Assert.Equal("PassWord=PLACEHOLDERabc123;uSER iD=someuser;DaTa SoUrCe=testdb", sb.ConnectionString); // embedded equal sign in the value will cause the value to be // delimited with double-quotes sb = new DbConnectionStringBuilder(); sb["Password"] = "PLACEHOLDER=def"; sb["Data Source"] = "testdb"; sb["User ID"] = "someuser"; Assert.Equal("Password=\"PLACEHOLDER=def\";Data Source=testdb;User ID=someuser", sb.ConnectionString); // embedded semicolon in the value will cause the value to be // delimited with double-quotes sb = new DbConnectionStringBuilder(); sb["Password"] = "PLACEHOLDER;def"; sb["Data Source"] = "testdb"; sb["User ID"] = "someuser"; Assert.Equal("Password=\"PLACEHOLDER;def\";Data Source=testdb;User ID=someuser", sb.ConnectionString); // more right parentheses then left parentheses - happily takes it sb = new DbConnectionStringBuilder(); sb.ConnectionString = "Data Source=(((Blah=Something))))))"; Assert.Equal("data source=\"(((Blah=Something))))))\"", sb.ConnectionString); // more left curly braces then right curly braces - happily takes it sb = new DbConnectionStringBuilder(); sb.ConnectionString = "Data Source={{{{Blah=Something}}"; Assert.Equal("data source=\"{{{{Blah=Something}}\"", sb.ConnectionString); // spaces, empty string, null are treated like an empty string // and any previous settings is cleared sb.ConnectionString = " "; Assert.Equal(string.Empty, sb.ConnectionString); sb.ConnectionString = " "; Assert.Equal(string.Empty, sb.ConnectionString); sb.ConnectionString = ""; Assert.Equal(string.Empty, sb.ConnectionString); sb.ConnectionString = string.Empty; Assert.Equal(string.Empty, sb.ConnectionString); sb.ConnectionString = null; Assert.Equal(string.Empty, sb.ConnectionString); sb = new DbConnectionStringBuilder(); Assert.Equal(string.Empty, sb.ConnectionString); } [Fact] public void EmbeddedCharTest2() { DbConnectionStringBuilder sb; sb = new DbConnectionStringBuilder(); sb.ConnectionString = "Driver={SQL Server};Server=(local host);" + "Trusted_Connection=Yes Or No;Database=Adventure Works;"; Assert.Equal("{SQL Server}", sb["Driver"]); Assert.Equal("(local host)", sb["Server"]); Assert.Equal("Yes Or No", sb["Trusted_Connection"]); Assert.Equal("driver=\"{SQL Server}\";server=\"(local host)\";" + "trusted_connection=\"Yes Or No\";database=\"Adventure Works\"", sb.ConnectionString); sb = new DbConnectionStringBuilder(); sb.ConnectionString = "Driver={SQLServer};Server=(local);" + "Trusted_Connection=Yes;Database=AdventureWorks;"; Assert.Equal("{SQLServer}", sb["Driver"]); Assert.Equal("(local)", sb["Server"]); Assert.Equal("Yes", sb["Trusted_Connection"]); Assert.Equal("driver={SQLServer};server=(local);" + "trusted_connection=Yes;database=AdventureWorks", sb.ConnectionString); sb = new DbConnectionStringBuilder(false); sb.ConnectionString = "Driver={SQL Server};Server=(local host);" + "Trusted_Connection=Yes Or No;Database=Adventure Works;"; Assert.Equal("{SQL Server}", sb["Driver"]); Assert.Equal("(local host)", sb["Server"]); Assert.Equal("Yes Or No", sb["Trusted_Connection"]); Assert.Equal("driver=\"{SQL Server}\";server=\"(local host)\";" + "trusted_connection=\"Yes Or No\";database=\"Adventure Works\"", sb.ConnectionString); sb = new DbConnectionStringBuilder(false); sb.ConnectionString = "Driver={SQLServer};Server=(local);" + "Trusted_Connection=Yes;Database=AdventureWorks;"; Assert.Equal("{SQLServer}", sb["Driver"]); Assert.Equal("(local)", sb["Server"]); Assert.Equal("Yes", sb["Trusted_Connection"]); Assert.Equal("driver={SQLServer};server=(local);" + "trusted_connection=Yes;database=AdventureWorks", sb.ConnectionString); sb = new DbConnectionStringBuilder(true); sb.ConnectionString = "Driver={SQL Server};Server=(local host);" + "Trusted_Connection=Yes Or No;Database=Adventure Works;"; Assert.Equal("{SQL Server}", sb["Driver"]); Assert.Equal("(local host)", sb["Server"]); Assert.Equal("Yes Or No", sb["Trusted_Connection"]); Assert.Equal("driver={SQL Server};server=(local host);" + "trusted_connection=Yes Or No;database=Adventure Works", sb.ConnectionString); sb = new DbConnectionStringBuilder(true); sb.ConnectionString = "Driver={SQLServer};Server=(local);" + "Trusted_Connection=Yes;Database=AdventureWorks;"; Assert.Equal("{SQLServer}", sb["Driver"]); Assert.Equal("(local)", sb["Server"]); Assert.Equal("Yes", sb["Trusted_Connection"]); Assert.Equal("driver={SQLServer};server=(local);" + "trusted_connection=Yes;database=AdventureWorks", sb.ConnectionString); } [Fact] public void EmbeddedCharTest3() { string dataSource = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.1.101)" + "(PORT=1521))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=TESTDB)))"; DbConnectionStringBuilder sb; sb = new DbConnectionStringBuilder(); sb.ConnectionString = "User ID=SCOTT;Password=PLACEHOLDER;Data Source=" + dataSource; Assert.Equal(dataSource, sb["Data Source"]); Assert.Equal("SCOTT", sb["User ID"]); Assert.Equal("PLACEHOLDER", sb["Password"]); Assert.Equal( "user id=SCOTT;password=PLACEHOLDER;data source=\"(DESCRIPTION=(ADDRESS=(PROTOCOL=" + "TCP)(HOST=192.168.1.101)(PORT=1521))(CONNECT_DATA=(SERVER=DEDICATED)" + "(SERVICE_NAME=TESTDB)))\"", sb.ConnectionString); sb = new DbConnectionStringBuilder(false); sb.ConnectionString = "User ID=SCOTT;Password=PLACEHOLDER;Data Source=" + dataSource; Assert.Equal(dataSource, sb["Data Source"]); Assert.Equal("SCOTT", sb["User ID"]); Assert.Equal("PLACEHOLDER", sb["Password"]); Assert.Equal( "user id=SCOTT;password=PLACEHOLDER;data source=\"(DESCRIPTION=(ADDRESS=(PROTOCOL=" + "TCP)(HOST=192.168.1.101)(PORT=1521))(CONNECT_DATA=(SERVER=DEDICATED)" + "(SERVICE_NAME=TESTDB)))\"", sb.ConnectionString); sb = new DbConnectionStringBuilder(true); sb.ConnectionString = "User ID=SCOTT;Password=PLACEHOLDER;Data Source=" + dataSource; Assert.Equal(dataSource, sb["Data Source"]); Assert.Equal("SCOTT", sb["User ID"]); Assert.Equal("PLACEHOLDER", sb["Password"]); Assert.Equal( "user id=SCOTT;password=PLACEHOLDER;data source=(DESCRIPTION=(ADDRESS=(PROTOCOL=" + "TCP)(HOST=192.168.1.101)(PORT=1521))(CONNECT_DATA=(SERVER=DEDICATED)" + "(SERVICE_NAME=TESTDB)))", sb.ConnectionString); } [Fact] public void EmbeddedCharTest4() { DbConnectionStringBuilder sb; sb = new DbConnectionStringBuilder(); sb.ConnectionString = "PassWord=PLACEHOLDER;user iD=someuser;DaTa SoUrCe=testdb"; sb["Integrated Security"] = "False"; Assert.Equal( "password=PLACEHOLDER;user id=someuser;data source=testdb;Integrated Security=False", sb.ConnectionString); sb = new DbConnectionStringBuilder(false); sb.ConnectionString = "PassWord=PLACEHOLDER;uSER iD=someuser;DaTa SoUrCe=testdb"; sb["Integrated Security"] = "False"; Assert.Equal( "password=PLACEHOLDER;user id=someuser;data source=testdb;Integrated Security=False", sb.ConnectionString); sb = new DbConnectionStringBuilder(true); sb.ConnectionString = "PassWord=PLACEHOLDER;uSER iD=someuser;DaTa SoUrCe=testdb"; sb["Integrated Security"] = "False"; Assert.Equal( "password=PLACEHOLDER;user id=someuser;data source=testdb;Integrated Security=False", sb.ConnectionString); } [Fact] public void EmbeddedCharTest5() { string connectionString = "A={abcdef2};B=some{us;C=test}db;D=12\"3;E=\"45;6\";F=AB==C;G{A'}\";F={1='\"2};G==C=B==C;Z=ABC"; DbConnectionStringBuilder sb; sb = new DbConnectionStringBuilder(); sb.ConnectionString = connectionString; Assert.Equal("a={abcdef2};b=some{us;c=test}db;d='12\"3';e=\"45;6\";f=\"AB==C\";g{a'}\";f=\"{1='\"\"2}\";g==c=\"B==C\";z=ABC", sb.ConnectionString); Assert.Equal("{abcdef2}", sb["A"]); Assert.Equal("some{us", sb["B"]); Assert.Equal("test}db", sb["C"]); Assert.Equal("12\"3", sb["D"]); Assert.Equal("45;6", sb["E"]); Assert.Equal("AB==C", sb["F"]); Assert.Equal("{1='\"2}", sb["g{a'}\";f"]); Assert.Equal("ABC", sb["Z"]); Assert.Equal("B==C", sb["g=c"]); sb = new DbConnectionStringBuilder(false); sb.ConnectionString = connectionString; Assert.Equal("a={abcdef2};b=some{us;c=test}db;d='12\"3';e=\"45;6\";f=\"AB==C\";g{a'}\";f=\"{1='\"\"2}\";g==c=\"B==C\";z=ABC", sb.ConnectionString); Assert.Equal("{abcdef2}", sb["A"]); Assert.Equal("some{us", sb["B"]); Assert.Equal("test}db", sb["C"]); Assert.Equal("12\"3", sb["D"]); Assert.Equal("45;6", sb["E"]); Assert.Equal("AB==C", sb["F"]); Assert.Equal("{1='\"2}", sb["g{a'}\";f"]); Assert.Equal("ABC", sb["Z"]); Assert.Equal("B==C", sb["g=c"]); sb = new DbConnectionStringBuilder(true); sb.ConnectionString = connectionString; Assert.Equal("a={abcdef2};b=some{us;c=test}db;d=12\"3;e=\"45;6\";f=AB==C;g{a'}\";f={1='\"2};g==C=B==C;z=ABC", sb.ConnectionString); Assert.Equal("{abcdef2}", sb["A"]); Assert.Equal("some{us", sb["B"]); Assert.Equal("test}db", sb["C"]); Assert.Equal("12\"3", sb["D"]); Assert.Equal("\"45", sb["E"]); Assert.Equal("AB==C", sb["6\";f"]); Assert.Equal("{1='\"2}", sb["g{a'}\";f"]); Assert.Equal("ABC", sb["Z"]); Assert.Equal("=C=B==C", sb["g"]); } [Fact] public void EmbeddedCharTest6() { string[][] shared_tests = new string[][] { new string [] { "A=(B;", "A", "(B", "a=(B" }, new string [] { "A={B{}", "A", "{B{}", "a={B{}" }, new string [] { "A={B{{}", "A", "{B{{}", "a={B{{}" }, new string [] { " A =B{C", "A", "B{C", "a=B{C" }, new string [] { " A =B{{C}", "A", "B{{C}", "a=B{{C}" }, new string [] { "A={{{B}}}", "A", "{{{B}}}", "a={{{B}}}" }, new string [] { "A={B}", "A", "{B}", "a={B}" }, new string [] { "A= {B}", "A", "{B}", "a={B}" }, new string [] { " A =BC", "a", "BC", "a=BC" }, new string [] { "\rA\t=BC", "a", "BC", "a=BC" }, new string [] { "\rA\t=BC", "a", "BC", "a=BC" }, new string [] { "A;B=BC", "a;b", "BC", "a;b=BC" }, }; string[][] non_odbc_tests = new string[][] { new string [] { "A=''", "A", "", "a=" }, new string [] { "A='BC;D'", "A", "BC;D", "a=\"BC;D\"" }, new string [] { "A=BC''D", "A", "BC''D", "a=\"BC''D\"" }, new string [] { "A='\"'", "A", "\"", "a='\"'" }, new string [] { "A=B\"\"C;", "A", "B\"\"C", "a='B\"\"C'" }, new string [] { "A={B{", "A", "{B{", "a={B{" }, new string [] { "A={B}C", "A", "{B}C", "a={B}C" }, new string [] { "A=B'C", "A", "B'C", "a=\"B'C\"" }, new string [] { "A=B''C", "A", "B''C", "a=\"B''C\"" }, new string [] { "A= B C ;", "A", "B C", "a=\"B C\"" }, new string [] { "A={B { }} }", "A", "{B { }} }", "a=\"{B { }} }\"" }, new string [] { "A={B {{ }} }", "A", "{B {{ }} }", "a=\"{B {{ }} }\"" }, new string [] { "A= B {C ", "A", "B {C", "a=\"B {C\"" }, new string [] { "A= B }C ", "A", "B }C", "a=\"B }C\"" }, new string [] { "A=B }C", "A", "B }C", "a=\"B }C\"" }, new string [] { "A=B { }C", "A", "B { }C", "a=\"B { }C\"" }, new string [] { "A= B{C {}}", "A", "B{C {}}", "a=\"B{C {}}\"" }, new string [] { "A= {C {};B=A", "A", "{C {}", "a=\"{C {}\";b=A" }, new string [] { "A= {C {} ", "A", "{C {}", "a=\"{C {}\"" }, new string [] { "A= {C {} ;B=A", "A", "{C {}", "a=\"{C {}\";b=A" }, new string [] { "A= {C {}}}", "A", "{C {}}}", "a=\"{C {}}}\"" }, new string [] { "A={B=C}", "A", "{B=C}", "a=\"{B=C}\"" }, new string [] { "A={B==C}", "A", "{B==C}", "a=\"{B==C}\"" }, new string [] { "A=B==C", "A", "B==C", "a=\"B==C\"" }, new string [] { "A={=}", "A", "{=}", "a=\"{=}\"" }, new string [] { "A={==}", "A", "{==}", "a=\"{==}\"" }, new string [] { "A=\"B;(C)'\"", "A", "B;(C)'", "a=\"B;(C)'\"" }, new string [] { "A=B(=)C", "A", "B(=)C", "a=\"B(=)C\"" }, new string [] { "A=B=C", "A", "B=C", "a=\"B=C\"" }, new string [] { "A=B(==)C", "A", "B(==)C", "a=\"B(==)C\"" }, new string [] { "A=B C", "A", "B C", "a=\"B C\"" }, new string [] { "A= B C ", "A", "B C", "a=\"B C\"" }, new string [] { "A= B C ", "A", "B C", "a=\"B C\"" }, new string [] { "A=' B C '", "A", " B C ", "a=\" B C \"" }, new string [] { "A=\" B C \"", "A", " B C ", "a=\" B C \"" }, new string [] { "A={ B C }", "A", "{ B C }", "a=\"{ B C }\"" }, new string [] { "A= B C ;", "A", "B C", "a=\"B C\"" }, new string [] { "A= B\rC\r\t;", "A", "B\rC", "a=\"B\rC\"" }, new string [] { "A=\"\"\"B;C\"\"\"", "A", "\"B;C\"", "a='\"B;C\"'" }, new string [] { "A= \"\"\"B;C\"\"\" ", "A", "\"B;C\"", "a='\"B;C\"'" }, new string [] { "A='''B;C'''", "A", "'B;C'", "a=\"'B;C'\"" }, new string [] { "A= '''B;C''' ", "A", "'B;C'", "a=\"'B;C'\"" }, new string [] { "A={{", "A", "{{", "a={{" }, new string [] { "A={B C}", "A", "{B C}", "a=\"{B C}\"" }, new string [] { "A={ B C }", "A", "{ B C }", "a=\"{ B C }\"" }, new string [] { "A={B {{ } }", "A", "{B {{ } }", "a=\"{B {{ } }\"" }, new string [] { "A='='", "A", "=", "a=\"=\"" }, new string [] { "A='=='", "A", "==", "a=\"==\"" }, new string [] { "A=\"=\"", "A", "=", "a=\"=\"" }, new string [] { "A=\"==\"", "A", "==", "a=\"==\"" }, new string [] { "A={B}}", "A", "{B}}", "a={B}}" }, new string [] { "A=\";\"", "A", ";", "a=\";\"" }, new string [] { "A(=)=B", "A(", ")=B", "a(=\")=B\"" }, new string [] { "A==B=C", "A=B", "C", "a==b=C" }, new string [] { "A===B=C", "A=", "B=C", "a===\"B=C\"" }, new string [] { "(A=)=BC", "(a", ")=BC", "(a=\")=BC\"" }, new string [] { "A==C=B==C", "a=c", "B==C", "a==c=\"B==C\"" }, }; DbConnectionStringBuilder sb; for (int i = 0; i < non_odbc_tests.Length; i++) { string[] test = non_odbc_tests[i]; sb = new DbConnectionStringBuilder(); sb.ConnectionString = test[0]; Assert.Equal(test[3], sb.ConnectionString); Assert.Equal(test[2], sb[test[1]]); } for (int i = 0; i < non_odbc_tests.Length; i++) { string[] test = non_odbc_tests[i]; sb = new DbConnectionStringBuilder(false); sb.ConnectionString = test[0]; Assert.Equal(test[3], sb.ConnectionString); Assert.Equal(test[2], sb[test[1]]); } for (int i = 0; i < shared_tests.Length; i++) { string[] test = shared_tests[i]; sb = new DbConnectionStringBuilder(); sb.ConnectionString = test[0]; Assert.Equal(test[3], sb.ConnectionString); Assert.Equal(test[2], sb[test[1]]); } for (int i = 0; i < shared_tests.Length; i++) { string[] test = shared_tests[i]; sb = new DbConnectionStringBuilder(false); sb.ConnectionString = test[0]; Assert.Equal(test[3], sb.ConnectionString); Assert.Equal(test[2], sb[test[1]]); } string[][] odbc_tests = new string[][] { new string [] { "A=B(=)C", "A", "B(=)C", "a=B(=)C" }, new string [] { "A=B(==)C", "A", "B(==)C", "a=B(==)C" }, new string [] { "A= B C ;", "A", "B C", "a=B C" }, new string [] { "A= B\rC\r\t;", "A", "B\rC", "a=B\rC" }, new string [] { "A='''", "A", "'''", "a='''" }, new string [] { "A=''", "A", "''", "a=''" }, new string [] { "A=''B", "A", "''B", "a=''B" }, new string [] { "A=BC''D", "A", "BC''D", "a=BC''D" }, new string [] { "A='\"'", "A", "'\"'", "a='\"'" }, new string [] { "A=\"\"B", "A", "\"\"B", "a=\"\"B"}, new string [] { "A=B\"\"C;", "A", "B\"\"C", "a=B\"\"C" }, new string [] { "A=\"B", "A", "\"B", "a=\"B" }, new string [] { "A=\"", "A", "\"", "a=\"" }, new string [] { "A=B'C", "A", "B'C", "a=B'C" }, new string [] { "A=B''C", "A", "B''C", "a=B''C" }, new string [] { "A='A'C", "A", "'A'C", "a='A'C" }, new string [] { "A=B C", "A", "B C", "a=B C" }, new string [] { "A= B C ", "A", "B C", "a=B C" }, new string [] { "A= B C ", "A", "B C", "a=B C" }, new string [] { "A=' B C '", "A", "' B C '", "a=' B C '" }, new string [] { "A=\" B C \"", "A", "\" B C \"", "a=\" B C \"" }, new string [] { "A={ B C }", "A", "{ B C }", "a={ B C }" }, new string [] { "A= B C ;", "A", "B C", "a=B C" }, new string [] { "A=\"\"BC\"\"", "A", "\"\"BC\"\"", "a=\"\"BC\"\"" }, new string [] { "A=\"\"B\"C\"\";", "A", "\"\"B\"C\"\"", "a=\"\"B\"C\"\"" }, new string [] { "A= \"\"B\"C\"\" ", "A", "\"\"B\"C\"\"", "a=\"\"B\"C\"\"" }, new string [] { "A=''BC''", "A", "''BC''", "a=''BC''" }, new string [] { "A=''B'C'';", "A", "''B'C''", "a=''B'C''" }, new string [] { "A= ''B'C'' ", "A", "''B'C''", "a=''B'C''" }, new string [] { "A={B C}", "A", "{B C}", "a={B C}" }, new string [] { "A={ B C }", "A", "{ B C }", "a={ B C }" }, new string [] { "A={ B;C }", "A", "{ B;C }", "a={ B;C }" }, new string [] { "A={B { }} }", "A", "{B { }} }", "a={B { }} }" }, new string [] { "A={ B;= {;=}};= }", "A", "{ B;= {;=}};= }", "a={ B;= {;=}};= }" }, new string [] { "A={B {{ }} }", "A", "{B {{ }} }", "a={B {{ }} }" }, new string [] { "A={ B;= {{:= }};= }", "A", "{ B;= {{:= }};= }", "a={ B;= {{:= }};= }" }, new string [] { "A= B {C ", "A", "B {C", "a=B {C" }, new string [] { "A= B }C ", "A", "B }C", "a=B }C" }, new string [] { "A=B }C", "A", "B }C", "a=B }C" }, new string [] { "A=B { }C", "A", "B { }C", "a=B { }C" }, new string [] { "A= {B;{}", "A", "{B;{}", "a={B;{}" }, new string [] { "A= {B;{}}}", "A", "{B;{}}}", "a={B;{}}}" }, new string [] { "A= B{C {}}", "A", "B{C {}}", "a=B{C {}}" }, new string [] { "A= {C {};B=A", "A", "{C {}", "a={C {};b=A" }, new string [] { "A= {C {} ", "A", "{C {}", "a={C {}" }, new string [] { "A= {C {} ;B=A", "A", "{C {}", "a={C {};b=A" }, new string [] { "A= {C {}}}", "A", "{C {}}}", "a={C {}}}" }, new string [] { "A={B=C}", "A", "{B=C}", "a={B=C}" }, new string [] { "A={B==C}", "A", "{B==C}", "a={B==C}" }, new string [] { "A=B==C", "A", "B==C", "a=B==C" }, new string [] { "A='='", "A", "'='", "a='='" }, new string [] { "A='=='", "A", "'=='", "a='=='" }, new string [] { "A=\"=\"", "A", "\"=\"", "a=\"=\"" }, new string [] { "A=\"==\"", "A", "\"==\"", "a=\"==\"" }, new string [] { "A={=}", "A", "{=}", "a={=}" }, new string [] { "A={==}", "A", "{==}", "a={==}" }, new string [] { "A=B=C", "A", "B=C", "a=B=C" }, new string [] { "A(=)=B", "A(", ")=B", "a(=)=B" }, new string [] { "A==B=C", "A", "=B=C", "a==B=C" }, new string [] { "A===B=C", "A", "==B=C", "a===B=C" }, new string [] { "A'='=B=C", "A'", "'=B=C", "a'='=B=C" }, new string [] { "A\"=\"=B=C", "A\"", "\"=B=C", "a\"=\"=B=C" }, new string [] { "\"A=\"=BC", "\"a", "\"=BC", "\"a=\"=BC" }, new string [] { "(A=)=BC", "(a", ")=BC", "(a=)=BC" }, new string [] { "A==C=B==C", "A", "=C=B==C", "a==C=B==C" }, }; for (int i = 0; i < odbc_tests.Length; i++) { string[] test = odbc_tests[i]; sb = new DbConnectionStringBuilder(true); sb.ConnectionString = test[0]; Assert.Equal(test[3], sb.ConnectionString); Assert.Equal(test[2], sb[test[1]]); } for (int i = 0; i < shared_tests.Length; i++) { string[] test = shared_tests[i]; sb = new DbConnectionStringBuilder(true); sb.ConnectionString = test[0]; Assert.Equal(test[3], sb.ConnectionString); Assert.Equal(test[2], sb[test[1]]); } // each test that is in odbc_tests and not in non_odbc_tests // (or vice versa) should result in an ArgumentException AssertValueTest(non_odbc_tests, odbc_tests, true); AssertValueTest(odbc_tests, non_odbc_tests, false); } [Fact] public void EmbeddedChar_ConnectionString_Invalid() { string[] tests = new string[] { " =", "=", "=;", "=ABC;", "='A'", "A", "A=(B;)", "A=B';'C", "A=B { {;} }", "A=B { ; }C", "A=BC'E;F'D", }; DbConnectionStringBuilder[] cbs = new DbConnectionStringBuilder[] { new DbConnectionStringBuilder (), new DbConnectionStringBuilder (false), new DbConnectionStringBuilder (true) }; for (int i = 0; i < tests.Length; i++) { for (int j = 0; j < cbs.Length; j++) { DbConnectionStringBuilder cb = cbs[j]; try { cb.ConnectionString = tests[i]; Assert.False(true); } catch (ArgumentException ex) { // Format of the initialization string does // not conform to specification starting // at index 0 Assert.Equal(typeof(ArgumentException), ex.GetType()); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Null(ex.ParamName); } } } } private void AssertValueTest(string[][] tests1, string[][] tests2, bool useOdbc) { DbConnectionStringBuilder sb = new DbConnectionStringBuilder(useOdbc); for (int i = 0; i < tests1.Length; i++) { string[] test1 = tests1[i]; bool found = false; for (int j = 0; j < tests2.Length; j++) { string[] test2 = tests2[j]; if (test2[0] == test1[0]) { found = true; if (test2[1] != test1[1]) continue; if (test2[2] != test1[2]) continue; if (test2[3] != test1[3]) continue; Assert.False(true); } } if (found) continue; ArgumentException ex = Assert.Throws<ArgumentException>(() => sb.ConnectionString = test1[0]); // Format of the initialization string does // not conform to specification starting // at index 0 Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Null(ex.ParamName); } // check uniqueness of tests for (int i = 0; i < tests1.Length; i++) { for (int j = 0; j < tests1.Length; j++) { if (i == j) continue; Assert.NotEqual(tests1[i], tests1[j]); } } // check uniqueness of tests for (int i = 0; i < tests2.Length; i++) { for (int j = 0; j < tests2.Length; j++) { if (i == j) continue; Assert.NotEqual(tests2[i], tests2[j]); } } } } }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/tests/JIT/jit64/regress/ddb/87766/ddb87766.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <PropertyGroup> <JitOptimizationSensitive>true</JitOptimizationSensitive> </PropertyGroup> <ItemGroup> <Compile Include="ddb87766.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <PropertyGroup> <JitOptimizationSensitive>true</JitOptimizationSensitive> </PropertyGroup> <ItemGroup> <Compile Include="ddb87766.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerCollection.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; namespace System.ComponentModel.Design { /// <summary> /// Provides a read-only collection of documents. /// </summary> public class DesignerCollection : ICollection { private readonly IList _designers; /// <summary> /// Initializes a new instance of the <see cref='System.ComponentModel.Design.DesignerCollection'/> class /// that stores an array with a pointer to each <see cref='System.ComponentModel.Design.IDesignerHost'/> /// for each document in the collection. /// </summary> public DesignerCollection(IDesignerHost[]? designers) { if (designers != null) { _designers = new ArrayList(designers); } else { _designers = new ArrayList(); } } /// <summary> /// Initializes a new instance of the <see cref='System.ComponentModel.Design.DesignerCollection'/> class /// that stores an array with a pointer to each <see cref='System.ComponentModel.Design.IDesignerHost'/> /// for each document in the collection. /// </summary> public DesignerCollection(IList? designers) { _designers = designers ?? new ArrayList(); } /// <summary> /// Gets or sets the number of documents in the collection. /// </summary> public int Count => _designers.Count; /// <summary> /// Gets or sets the document at the specified index. /// </summary> public virtual IDesignerHost? this[int index] => (IDesignerHost?)_designers[index]; /// <summary> /// Creates and retrieves a new enumerator for this collection. /// </summary> public IEnumerator GetEnumerator() => _designers.GetEnumerator(); int ICollection.Count => Count; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => null!; void ICollection.CopyTo(Array array, int index) => _designers.CopyTo(array, index); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; namespace System.ComponentModel.Design { /// <summary> /// Provides a read-only collection of documents. /// </summary> public class DesignerCollection : ICollection { private readonly IList _designers; /// <summary> /// Initializes a new instance of the <see cref='System.ComponentModel.Design.DesignerCollection'/> class /// that stores an array with a pointer to each <see cref='System.ComponentModel.Design.IDesignerHost'/> /// for each document in the collection. /// </summary> public DesignerCollection(IDesignerHost[]? designers) { if (designers != null) { _designers = new ArrayList(designers); } else { _designers = new ArrayList(); } } /// <summary> /// Initializes a new instance of the <see cref='System.ComponentModel.Design.DesignerCollection'/> class /// that stores an array with a pointer to each <see cref='System.ComponentModel.Design.IDesignerHost'/> /// for each document in the collection. /// </summary> public DesignerCollection(IList? designers) { _designers = designers ?? new ArrayList(); } /// <summary> /// Gets or sets the number of documents in the collection. /// </summary> public int Count => _designers.Count; /// <summary> /// Gets or sets the document at the specified index. /// </summary> public virtual IDesignerHost? this[int index] => (IDesignerHost?)_designers[index]; /// <summary> /// Creates and retrieves a new enumerator for this collection. /// </summary> public IEnumerator GetEnumerator() => _designers.GetEnumerator(); int ICollection.Count => Count; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => null!; void ICollection.CopyTo(Array array, int index) => _designers.CopyTo(array, index); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/tests/JIT/IL_Conformance/Old/Base/dup.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <RestorePackages>true</RestorePackages> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="dup.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <RestorePackages>true</RestorePackages> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="dup.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/RoAssembly.GetForwardedTypes.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Collections.Generic; namespace System.Reflection.TypeLoading { /// <summary> /// Base class for all Assembly objects created by a MetadataLoadContext. /// </summary> internal abstract partial class RoAssembly { public sealed override Type[] GetForwardedTypes() { List<Type> types = new List<Type>(); List<Exception>? exceptions = null; IterateTypeForwards( delegate (RoAssembly redirectedAssembly, ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name) { Type? type = null; Exception? exception = null; if (redirectedAssembly is RoExceptionAssembly exceptionAssembly) { exception = exceptionAssembly.Exception; } else { // GetTypeCore() will follow any further type-forwards if needed. type = redirectedAssembly.GetTypeCore(ns, name, ignoreCase: false, out Exception? e); if (type == null) { exception = e; } } Debug.Assert((type != null) != (exception != null)); // Exactly one of these must be non-null. if (type != null) { types.Add(type); AddPublicNestedTypes(type, types); } else { if (exceptions == null) { exceptions = new List<Exception>(); } exceptions.Add(exception!); } } ); if (exceptions != null) { int numTypes = types.Count; int numExceptions = exceptions.Count; types.AddRange(new Type[numExceptions]); // add one null Type for each exception. exceptions.InsertRange(0, new Exception[numTypes]); // align the Exceptions with the null Types. throw new ReflectionTypeLoadException(types.ToArray(), exceptions.ToArray()); } return types.ToArray(); } private static void AddPublicNestedTypes(Type type, List<Type> types) { foreach (Type nestedType in type.GetNestedTypes(BindingFlags.Public)) { types.Add(nestedType); AddPublicNestedTypes(nestedType, types); } } /// <summary> /// Intentionally excludes forwards to nested types. /// </summary> protected delegate void TypeForwardHandler(RoAssembly redirectedAssembly, ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name); protected abstract void IterateTypeForwards(TypeForwardHandler handler); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Collections.Generic; namespace System.Reflection.TypeLoading { /// <summary> /// Base class for all Assembly objects created by a MetadataLoadContext. /// </summary> internal abstract partial class RoAssembly { public sealed override Type[] GetForwardedTypes() { List<Type> types = new List<Type>(); List<Exception>? exceptions = null; IterateTypeForwards( delegate (RoAssembly redirectedAssembly, ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name) { Type? type = null; Exception? exception = null; if (redirectedAssembly is RoExceptionAssembly exceptionAssembly) { exception = exceptionAssembly.Exception; } else { // GetTypeCore() will follow any further type-forwards if needed. type = redirectedAssembly.GetTypeCore(ns, name, ignoreCase: false, out Exception? e); if (type == null) { exception = e; } } Debug.Assert((type != null) != (exception != null)); // Exactly one of these must be non-null. if (type != null) { types.Add(type); AddPublicNestedTypes(type, types); } else { if (exceptions == null) { exceptions = new List<Exception>(); } exceptions.Add(exception!); } } ); if (exceptions != null) { int numTypes = types.Count; int numExceptions = exceptions.Count; types.AddRange(new Type[numExceptions]); // add one null Type for each exception. exceptions.InsertRange(0, new Exception[numTypes]); // align the Exceptions with the null Types. throw new ReflectionTypeLoadException(types.ToArray(), exceptions.ToArray()); } return types.ToArray(); } private static void AddPublicNestedTypes(Type type, List<Type> types) { foreach (Type nestedType in type.GetNestedTypes(BindingFlags.Public)) { types.Add(nestedType); AddPublicNestedTypes(nestedType, types); } } /// <summary> /// Intentionally excludes forwards to nested types. /// </summary> protected delegate void TypeForwardHandler(RoAssembly redirectedAssembly, ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name); protected abstract void IterateTypeForwards(TypeForwardHandler handler); } }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/libraries/System.ServiceModel.Syndication/tests/TestFeeds/AtomFeeds/generator-escaped-html.xml
<!-- Description: generator with text that appears to contain escaped HTML produces a warning Expect: ContainsHTML{element:generator,parent:feed} --> <feed xmlns="http://www.w3.org/2005/Atom"> <title>Example Feed</title> <link href="http://contoso.com/"/> <updated>2003-12-13T18:30:02Z</updated> <author> <name>Author Name</name> </author> <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id> <generator uri="/generator">&lt;b&gt;The&lt;/b&gt; generator</generator> <entry> <title>Atom-Powered Robots Run Amok</title> <link href="http://contoso.com/2003/12/13/atom03"/> <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> <updated>2003-12-13T18:30:02Z</updated> <summary>Some text.</summary> </entry> </feed>
<!-- Description: generator with text that appears to contain escaped HTML produces a warning Expect: ContainsHTML{element:generator,parent:feed} --> <feed xmlns="http://www.w3.org/2005/Atom"> <title>Example Feed</title> <link href="http://contoso.com/"/> <updated>2003-12-13T18:30:02Z</updated> <author> <name>Author Name</name> </author> <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id> <generator uri="/generator">&lt;b&gt;The&lt;/b&gt; generator</generator> <entry> <title>Atom-Powered Robots Run Amok</title> <link href="http://contoso.com/2003/12/13/atom03"/> <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> <updated>2003-12-13T18:30:02Z</updated> <summary>Some text.</summary> </entry> </feed>
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/libraries/System.IO.Ports/src/System.IO.Ports.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <DefineConstants>$(DefineConstants);SERIAL_PORTS</DefineConstants> <IncludeDllSafeSearchPathAttribute>true</IncludeDllSafeSearchPathAttribute> <Nullable>annotations</Nullable> <TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)-Unix;$(NetCoreAppCurrent);$(NetCoreAppMinimum)-windows;$(NetCoreAppMinimum)-Unix;$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks> <IsPackable>true</IsPackable> <PackageDescription>Provides classes for controlling serial ports. Commonly Used Types: System.IO.Ports.SerialPort</PackageDescription> </PropertyGroup> <!-- DesignTimeBuild requires all the TargetFramework Derived Properties to not be present in the first property group. --> <PropertyGroup> <TargetPlatformIdentifier>$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)'))</TargetPlatformIdentifier> <IsPartialFacadeAssembly Condition="$([MSBuild]::GetTargetFrameworkIdentifier('$(TargetFramework)')) == '.NETFramework'">true</IsPartialFacadeAssembly> <GeneratePlatformNotSupportedAssemblyMessage Condition="'$(IsPartialFacadeAssembly)' != 'true' and '$(TargetPlatformIdentifier)' == ''">SR.PlatformNotSupported_IOPorts</GeneratePlatformNotSupportedAssemblyMessage> </PropertyGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' != ''"> <Compile Include="System\IO\Ports\Handshake.cs" /> <Compile Include="System\IO\Ports\InternalResources.cs" /> <Compile Include="System\IO\Ports\Parity.cs" /> <Compile Include="System\IO\Ports\SerialData.cs" /> <Compile Include="System\IO\Ports\SerialDataReceivedEventArgs.cs" /> <Compile Include="System\IO\Ports\SerialDataReceivedEventHandler.cs" /> <Compile Include="System\IO\Ports\SerialError.cs" /> <Compile Include="System\IO\Ports\SerialErrorReceivedEventArgs.cs" /> <Compile Include="System\IO\Ports\SerialErrorReceivedEventHandler.cs" /> <Compile Include="System\IO\Ports\SerialPinChange.cs" /> <Compile Include="System\IO\Ports\SerialPinChangedEventArgs.cs" /> <Compile Include="System\IO\Ports\SerialPinChangedEventHandler.cs" /> <Compile Include="System\IO\Ports\SerialPort.cs" /> <Compile Include="System\IO\Ports\SerialStream.cs" /> <Compile Include="System\IO\Ports\StopBits.cs" /> </ItemGroup> <ItemGroup Condition="$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net7.0')) and '$(TargetPlatformIdentifier)' != ''"> <Compile Include="$(CommonPath)DisableRuntimeMarshalling.cs" Link="Common\DisableRuntimeMarshalling.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'windows'"> <Compile Include="System\IO\Ports\SerialStream.Windows.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.DCB.cs" Link="Common\Interop\Windows\Kernel32\Interop.DCB.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.COMMPROP.cs" Link="Common\Interop\Windows\Kernel32\Interop.COMMPROP.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.COMMTIMEOUTS.cs" Link="Common\Interop\Windows\Kernel32\Interop.COMMTIMEOUTS.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.COMSTAT.cs" Link="Common\Interop\Windows\Kernel32\Interop.COMSTAT.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.SetCommState.cs" Link="Common\Interop\Windows\Kernel32\Interop.SetCommState.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.SetCommBreak.cs" Link="Common\Interop\Windows\Kernel32\Interop.SetCommBreak.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.ClearCommBreak.cs" Link="Common\Interop\Windows\Kernel32\Interop.ClearCommBreak.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.EscapeCommFunction.cs" Link="Common\Interop\Windows\Kernel32\Interop.EscapeCommFunction.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.SetCommTimeouts.cs" Link="Common\Interop\Windows\Kernel32\Interop.SetCommTimeouts.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetCommModemStatus.cs" Link="Common\Interop\Windows\Kernel32\Interop.GetCommModemStatus.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.ClearCommError.cs" Link="Common\Interop\Windows\Kernel32\Interop.ClearCommError.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetCommProperties.cs" Link="Common\Interop\Windows\Kernel32\Interop.GetCommProperties.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.SetCommMask.cs" Link="Common\Interop\Windows\Kernel32\Interop.SetCommMask.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.PurgeComm.cs" Link="Common\Interop\Windows\Kernel32\Interop.PurgeComm.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.SetupComm.cs" Link="Common\Interop\Windows\Kernel32\Interop.SetupComm.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetCommState.cs" Link="Common\Interop\Windows\Kernel32\Interop.GetCommState.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.WaitCommEvent.cs" Link="Common\Interop\Windows\Kernel32\Interop.WaitCommEvent.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.ReadFile_SafeHandle_IntPtr.cs" Link="Common\Interop\Windows\Kernel32\Interop.ReadFile_SafeHandle_IntPtr.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.ReadFile_SafeHandle_NativeOverlapped.cs" Link="Common\Interop\Windows\Kernel32\Interop.ReadFile_SafeHandle_NativeOverlapped.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.WriteFile_SafeHandle_IntPtr.cs" Link="Common\Interop\Windows\Kernel32\Interop.WriteFile_SafeHandle_IntPtr.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.WriteFile_SafeHandle_NativeOverlapped.cs" Link="Common\Interop\Windows\Kernel32\Interop.WriteFile_SafeHandle_NativeOverlapped.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetOverlappedResult.cs" Link="Common\Interop\Windows\Kernel32\Interop.GetOverlappedResult.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.FlushFileBuffers.cs" Link="Common\Interop\Windows\Kernel32\Interop.FlushFileBuffers.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GenericOperations.cs" Link="Common\Interop\Windows\Kernel32\Interop.GenericOperations.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.SECURITY_ATTRIBUTES.cs" Link="Common\Interop\Windows\Interop.SECURITY_ATTRIBUTES.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.FileTypes.cs" Link="Common\Interop\Windows\Interop.FileTypes.cs" /> <Compile Include="$(CommonPath)System\Text\ValueStringBuilder.cs" Link="Common\System\Text\ValueStringBuilder.cs" /> <Compile Include="$(CommonPath)System\IO\PathInternal.Windows.cs" Link="Common\System\IO\PathInternal.Windows.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetFileType_SafeHandle.cs" Link="Common\Interop\Windows\Kernel32\Interop.GetFileType_SafeHandle.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Interop.Libraries.cs" Link="Common\Interop\Windows\Interop.Libraries.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Interop.Errors.cs" Link="Common\Interop\Windows\Interop.Errors.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Interop.BOOL.cs" Link="Common\Interop\Windows\Interop.BOOL.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.CloseHandle.cs" Link="Common\Interop\Windows\Kernel32\Interop.CloseHandle.cs" /> <Compile Include="$(CommonPath)System\IO\Win32Marshal.cs" Link="Common\System\IO\Win32Marshal.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.FormatMessage.cs" Link="Common\Interop\Windows\Interop.FormatMessage.cs" /> <Compile Include="System\IO\Ports\SerialPort.Win32.cs" /> <Compile Include="System\IO\Ports\SerialStream.Win32.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.CreateFile.cs" Link="Common\Interop\Windows\Kernel32\Interop.CreateFile.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.FileOperations.cs" Link="Common\Interop\Windows\Kernel32\Interop.FileOperations.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'Unix'"> <Compile Include="System\IO\Ports\SafeSerialDeviceHandle.Unix.cs" /> <Compile Include="System\IO\Ports\SerialPort.Unix.cs" /> <Compile Include="System\IO\Ports\SerialStream.Unix.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.IO.Ports.Native\Interop.Termios.cs" Link="Common\Interop\Unix\System.IO.Ports.Native\Interop.Termios.cs"/> <Compile Include="$(CommonPath)Interop\Unix\System.IO.Ports.Native\Interop.Serial.cs" Link="Common\Interop\Unix\System.IO.Ports.Native\Interop.Serial.cs"/> <Compile Include="$(CommonPath)Interop\Unix\Interop.Libraries.cs" Link="Common\Interop\Unix\Interop.Libraries.cs" /> <Compile Include="$(CommonPath)Interop\Unix\Interop.Errors.cs" Link="Common\Interop\Unix\Interop.Errors.cs" /> <Compile Include="$(CommonPath)Interop\Unix\Interop.IOErrors.cs" Link="Common\Interop\Unix\Interop.IOErrors.cs" /> <Compile Include="$(CommonPath)Interop\Unix\Interop.Poll.Structs.cs" Link="Common\Interop\Unix\Interop.Poll.Structs.cs" /> <Compile Include="$(CommonPath)System\Threading\Tasks\TaskToApm.cs" Link="Common\System\Threading\Tasks\TaskToApm.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETCoreApp'"> <Reference Include="Microsoft.Win32.Primitives" /> <Reference Include="Microsoft.Win32.Registry" Condition="'$(TargetPlatformIdentifier)' == 'windows'" /> <Reference Include="System.Collections" /> <Reference Include="System.Collections.Concurrent" Condition="'$(TargetPlatformIdentifier)' == 'Unix'" /> <Reference Include="System.ComponentModel.Primitives" /> <Reference Include="System.Memory" /> <Reference Include="System.Net.Primitives" /> <Reference Include="System.Net.Sockets" Condition="'$(TargetPlatformIdentifier)' == 'Unix'" /> <Reference Include="System.Runtime" /> <Reference Include="System.Runtime.CompilerServices.Unsafe" /> <Reference Include="System.Runtime.InteropServices" /> <Reference Include="System.Runtime.InteropServices.RuntimeInformation" Condition="'$(TargetPlatformIdentifier)' == 'Unix'" /> <Reference Include="System.Text.Encoding.Extensions" /> <Reference Include="System.Threading" /> <Reference Include="System.Threading.Thread" /> <Reference Include="System.Threading.Overlapped" /> <Reference Include="System.Threading.ThreadPool" /> </ItemGroup> <ItemGroup Condition="'$(IsPartialFacadeAssembly)' != 'true'"> <!-- Just reference the runtime packages but don't build them in order to avoid unintentional Build/Pack invocations. --> <ProjectReference Include="..\pkg\runtime.native.$(MSBuildProjectName).proj" BuildReference="false" /> <!-- Make the runtime specific packages non transitive so that they aren't flowing into other projects. --> <ProjectReference Include="..\pkg\runtime.*.runtime.native.$(MSBuildProjectName).proj" BuildReference="false" PrivateAssets="all" /> </ItemGroup> <ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETStandard'"> <PackageReference Include="System.Memory" Version="$(SystemMemoryVersion)" /> <PackageReference Include="Microsoft.Win32.Registry" Version="$(MicrosoftWin32RegistryVersion)" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <DefineConstants>$(DefineConstants);SERIAL_PORTS</DefineConstants> <IncludeDllSafeSearchPathAttribute>true</IncludeDllSafeSearchPathAttribute> <Nullable>annotations</Nullable> <TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)-Unix;$(NetCoreAppCurrent);$(NetCoreAppMinimum)-windows;$(NetCoreAppMinimum)-Unix;$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks> <IsPackable>true</IsPackable> <PackageDescription>Provides classes for controlling serial ports. Commonly Used Types: System.IO.Ports.SerialPort</PackageDescription> </PropertyGroup> <!-- DesignTimeBuild requires all the TargetFramework Derived Properties to not be present in the first property group. --> <PropertyGroup> <TargetPlatformIdentifier>$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)'))</TargetPlatformIdentifier> <IsPartialFacadeAssembly Condition="$([MSBuild]::GetTargetFrameworkIdentifier('$(TargetFramework)')) == '.NETFramework'">true</IsPartialFacadeAssembly> <GeneratePlatformNotSupportedAssemblyMessage Condition="'$(IsPartialFacadeAssembly)' != 'true' and '$(TargetPlatformIdentifier)' == ''">SR.PlatformNotSupported_IOPorts</GeneratePlatformNotSupportedAssemblyMessage> </PropertyGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' != ''"> <Compile Include="System\IO\Ports\Handshake.cs" /> <Compile Include="System\IO\Ports\InternalResources.cs" /> <Compile Include="System\IO\Ports\Parity.cs" /> <Compile Include="System\IO\Ports\SerialData.cs" /> <Compile Include="System\IO\Ports\SerialDataReceivedEventArgs.cs" /> <Compile Include="System\IO\Ports\SerialDataReceivedEventHandler.cs" /> <Compile Include="System\IO\Ports\SerialError.cs" /> <Compile Include="System\IO\Ports\SerialErrorReceivedEventArgs.cs" /> <Compile Include="System\IO\Ports\SerialErrorReceivedEventHandler.cs" /> <Compile Include="System\IO\Ports\SerialPinChange.cs" /> <Compile Include="System\IO\Ports\SerialPinChangedEventArgs.cs" /> <Compile Include="System\IO\Ports\SerialPinChangedEventHandler.cs" /> <Compile Include="System\IO\Ports\SerialPort.cs" /> <Compile Include="System\IO\Ports\SerialStream.cs" /> <Compile Include="System\IO\Ports\StopBits.cs" /> </ItemGroup> <ItemGroup Condition="$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net7.0')) and '$(TargetPlatformIdentifier)' != ''"> <Compile Include="$(CommonPath)DisableRuntimeMarshalling.cs" Link="Common\DisableRuntimeMarshalling.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'windows'"> <Compile Include="System\IO\Ports\SerialStream.Windows.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.DCB.cs" Link="Common\Interop\Windows\Kernel32\Interop.DCB.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.COMMPROP.cs" Link="Common\Interop\Windows\Kernel32\Interop.COMMPROP.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.COMMTIMEOUTS.cs" Link="Common\Interop\Windows\Kernel32\Interop.COMMTIMEOUTS.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.COMSTAT.cs" Link="Common\Interop\Windows\Kernel32\Interop.COMSTAT.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.SetCommState.cs" Link="Common\Interop\Windows\Kernel32\Interop.SetCommState.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.SetCommBreak.cs" Link="Common\Interop\Windows\Kernel32\Interop.SetCommBreak.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.ClearCommBreak.cs" Link="Common\Interop\Windows\Kernel32\Interop.ClearCommBreak.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.EscapeCommFunction.cs" Link="Common\Interop\Windows\Kernel32\Interop.EscapeCommFunction.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.SetCommTimeouts.cs" Link="Common\Interop\Windows\Kernel32\Interop.SetCommTimeouts.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetCommModemStatus.cs" Link="Common\Interop\Windows\Kernel32\Interop.GetCommModemStatus.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.ClearCommError.cs" Link="Common\Interop\Windows\Kernel32\Interop.ClearCommError.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetCommProperties.cs" Link="Common\Interop\Windows\Kernel32\Interop.GetCommProperties.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.SetCommMask.cs" Link="Common\Interop\Windows\Kernel32\Interop.SetCommMask.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.PurgeComm.cs" Link="Common\Interop\Windows\Kernel32\Interop.PurgeComm.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.SetupComm.cs" Link="Common\Interop\Windows\Kernel32\Interop.SetupComm.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetCommState.cs" Link="Common\Interop\Windows\Kernel32\Interop.GetCommState.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.WaitCommEvent.cs" Link="Common\Interop\Windows\Kernel32\Interop.WaitCommEvent.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.ReadFile_SafeHandle_IntPtr.cs" Link="Common\Interop\Windows\Kernel32\Interop.ReadFile_SafeHandle_IntPtr.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.ReadFile_SafeHandle_NativeOverlapped.cs" Link="Common\Interop\Windows\Kernel32\Interop.ReadFile_SafeHandle_NativeOverlapped.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.WriteFile_SafeHandle_IntPtr.cs" Link="Common\Interop\Windows\Kernel32\Interop.WriteFile_SafeHandle_IntPtr.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.WriteFile_SafeHandle_NativeOverlapped.cs" Link="Common\Interop\Windows\Kernel32\Interop.WriteFile_SafeHandle_NativeOverlapped.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetOverlappedResult.cs" Link="Common\Interop\Windows\Kernel32\Interop.GetOverlappedResult.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.FlushFileBuffers.cs" Link="Common\Interop\Windows\Kernel32\Interop.FlushFileBuffers.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GenericOperations.cs" Link="Common\Interop\Windows\Kernel32\Interop.GenericOperations.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.SECURITY_ATTRIBUTES.cs" Link="Common\Interop\Windows\Interop.SECURITY_ATTRIBUTES.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.FileTypes.cs" Link="Common\Interop\Windows\Interop.FileTypes.cs" /> <Compile Include="$(CommonPath)System\Text\ValueStringBuilder.cs" Link="Common\System\Text\ValueStringBuilder.cs" /> <Compile Include="$(CommonPath)System\IO\PathInternal.Windows.cs" Link="Common\System\IO\PathInternal.Windows.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetFileType_SafeHandle.cs" Link="Common\Interop\Windows\Kernel32\Interop.GetFileType_SafeHandle.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Interop.Libraries.cs" Link="Common\Interop\Windows\Interop.Libraries.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Interop.Errors.cs" Link="Common\Interop\Windows\Interop.Errors.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Interop.BOOL.cs" Link="Common\Interop\Windows\Interop.BOOL.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.CloseHandle.cs" Link="Common\Interop\Windows\Kernel32\Interop.CloseHandle.cs" /> <Compile Include="$(CommonPath)System\IO\Win32Marshal.cs" Link="Common\System\IO\Win32Marshal.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.FormatMessage.cs" Link="Common\Interop\Windows\Interop.FormatMessage.cs" /> <Compile Include="System\IO\Ports\SerialPort.Win32.cs" /> <Compile Include="System\IO\Ports\SerialStream.Win32.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.CreateFile.cs" Link="Common\Interop\Windows\Kernel32\Interop.CreateFile.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.FileOperations.cs" Link="Common\Interop\Windows\Kernel32\Interop.FileOperations.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'Unix'"> <Compile Include="System\IO\Ports\SafeSerialDeviceHandle.Unix.cs" /> <Compile Include="System\IO\Ports\SerialPort.Unix.cs" /> <Compile Include="System\IO\Ports\SerialStream.Unix.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.IO.Ports.Native\Interop.Termios.cs" Link="Common\Interop\Unix\System.IO.Ports.Native\Interop.Termios.cs"/> <Compile Include="$(CommonPath)Interop\Unix\System.IO.Ports.Native\Interop.Serial.cs" Link="Common\Interop\Unix\System.IO.Ports.Native\Interop.Serial.cs"/> <Compile Include="$(CommonPath)Interop\Unix\Interop.Libraries.cs" Link="Common\Interop\Unix\Interop.Libraries.cs" /> <Compile Include="$(CommonPath)Interop\Unix\Interop.Errors.cs" Link="Common\Interop\Unix\Interop.Errors.cs" /> <Compile Include="$(CommonPath)Interop\Unix\Interop.IOErrors.cs" Link="Common\Interop\Unix\Interop.IOErrors.cs" /> <Compile Include="$(CommonPath)Interop\Unix\Interop.Poll.Structs.cs" Link="Common\Interop\Unix\Interop.Poll.Structs.cs" /> <Compile Include="$(CommonPath)System\Threading\Tasks\TaskToApm.cs" Link="Common\System\Threading\Tasks\TaskToApm.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETCoreApp'"> <Reference Include="Microsoft.Win32.Primitives" /> <Reference Include="Microsoft.Win32.Registry" Condition="'$(TargetPlatformIdentifier)' == 'windows'" /> <Reference Include="System.Collections" /> <Reference Include="System.Collections.Concurrent" Condition="'$(TargetPlatformIdentifier)' == 'Unix'" /> <Reference Include="System.ComponentModel.Primitives" /> <Reference Include="System.Memory" /> <Reference Include="System.Net.Primitives" /> <Reference Include="System.Net.Sockets" Condition="'$(TargetPlatformIdentifier)' == 'Unix'" /> <Reference Include="System.Runtime" /> <Reference Include="System.Runtime.CompilerServices.Unsafe" /> <Reference Include="System.Runtime.InteropServices" /> <Reference Include="System.Runtime.InteropServices.RuntimeInformation" Condition="'$(TargetPlatformIdentifier)' == 'Unix'" /> <Reference Include="System.Text.Encoding.Extensions" /> <Reference Include="System.Threading" /> <Reference Include="System.Threading.Thread" /> <Reference Include="System.Threading.Overlapped" /> <Reference Include="System.Threading.ThreadPool" /> </ItemGroup> <ItemGroup Condition="'$(IsPartialFacadeAssembly)' != 'true'"> <!-- Just reference the runtime packages but don't build them in order to avoid unintentional Build/Pack invocations. --> <ProjectReference Include="..\pkg\runtime.native.$(MSBuildProjectName).proj" BuildReference="false" /> <!-- Make the runtime specific packages non transitive so that they aren't flowing into other projects. --> <ProjectReference Include="..\pkg\runtime.*.runtime.native.$(MSBuildProjectName).proj" BuildReference="false" PrivateAssets="all" /> </ItemGroup> <ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETStandard'"> <PackageReference Include="System.Memory" Version="$(SystemMemoryVersion)" /> <PackageReference Include="Microsoft.Win32.Registry" Version="$(MicrosoftWin32RegistryVersion)" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/libraries/System.Data.Common/tests/System/Data/DataRowTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // (C) Copyright 2002 Franklin Wise // (C) Copyright 2003 Daniel Morgan // (C) Copyright 2003 Martin Willemoes Hansen // // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using Xunit; namespace System.Data.Tests { public class DataRowTest { private DataTable _table; private DataRow _row; public DataRowTest() { _table = MakeTable(); _row = _table.NewRow(); _row["FName"] = "Hello"; _row["LName"] = "World"; _table.Rows.Add(_row); } private DataTable MakeTable() { DataTable namesTable = new DataTable("Names"); DataColumn idColumn = new DataColumn(); idColumn.DataType = typeof(int); idColumn.ColumnName = "Id"; idColumn.AutoIncrement = true; namesTable.Columns.Add(idColumn); DataColumn fNameColumn = new DataColumn(); fNameColumn.DataType = typeof(string); fNameColumn.ColumnName = "Fname"; fNameColumn.DefaultValue = "Fname"; namesTable.Columns.Add(fNameColumn); DataColumn lNameColumn = new DataColumn(); lNameColumn.DataType = typeof(string); lNameColumn.ColumnName = "LName"; lNameColumn.DefaultValue = "LName"; namesTable.Columns.Add(lNameColumn); // Set the primary key for the table DataColumn[] keys = new DataColumn[1]; keys[0] = idColumn; namesTable.PrimaryKey = keys; // Return the new DataTable. return namesTable; } [Fact] public void SetColumnErrorTest() { string errorString; errorString = "Some error!"; // Set the error for the specified column of the row. _row.SetColumnError(1, errorString); GetColumnErrorTest(); GetAllErrorsTest(); } private void GetColumnErrorTest() { // Print the error of a specified column. Assert.Equal("Some error!", _row.GetColumnError(1)); } private void GetAllErrorsTest() { DataColumn[] colArr; if (_row.HasErrors) { colArr = _row.GetColumnsInError(); for (int i = 0; i < colArr.Length; i++) { Assert.Same(_table.Columns[1], colArr[i]); } _row.ClearErrors(); } } [Fact] public void DeleteRowTest() { DataRow newRow; for (int i = 1; i <= 2; i++) { newRow = _table.NewRow(); newRow["FName"] = "Name " + i; newRow["LName"] = " Last Name" + i; _table.Rows.Add(newRow); } _table.AcceptChanges(); for (int i = 1; i < _table.Rows.Count; i++) { DataRow r = _table.Rows[i]; Assert.Equal("Name " + i, r["fName"]); } // Create a DataView with the table. DataRowCollection rc = _table.Rows; rc[0].Delete(); rc[2].Delete(); Assert.Equal("Deleted", rc[0].RowState.ToString()); Assert.Equal("Deleted", rc[2].RowState.ToString()); // Accept changes _table.AcceptChanges(); Assert.Equal("Name 1", (_table.Rows[0])[1]); // There is no row at position 2. Assert.Throws<IndexOutOfRangeException>(() => rc[2]); } [Fact] public void ParentRowTest() { //Clear all existing values from table for (int i = 0; i < _table.Rows.Count; i++) { _table.Rows[i].Delete(); } _table.AcceptChanges(); _row = _table.NewRow(); _row["FName"] = "My FName"; _row["Id"] = 0; _table.Rows.Add(_row); DataTable tableC = new DataTable("Child"); DataColumn colC; DataRow rowC; colC = new DataColumn(); colC.DataType = typeof(int); colC.ColumnName = "Id"; colC.AutoIncrement = true; tableC.Columns.Add(colC); colC = new DataColumn(); colC.DataType = typeof(string); colC.ColumnName = "Name"; tableC.Columns.Add(colC); rowC = tableC.NewRow(); rowC["Name"] = "My FName"; tableC.Rows.Add(rowC); var ds = new DataSet(); ds.Tables.Add(_table); ds.Tables.Add(tableC); DataRelation dr = new DataRelation("PO", _table.Columns["Id"], tableC.Columns["Id"]); ds.Relations.Add(dr); rowC.SetParentRow(_table.Rows[0], dr); Assert.Equal(_table.Rows[0], (tableC.Rows[0]).GetParentRow(dr)); Assert.Equal(tableC.Rows[0], (_table.Rows[0]).GetChildRows(dr)[0]); ds.Relations.Clear(); dr = new DataRelation("PO", _table.Columns["Id"], tableC.Columns["Id"], false); ds.Relations.Add(dr); rowC.SetParentRow(_table.Rows[0], dr); Assert.Equal(_table.Rows[0], (tableC.Rows[0]).GetParentRow(dr)); Assert.Equal(tableC.Rows[0], (_table.Rows[0]).GetChildRows(dr)[0]); ds.Relations.Clear(); dr = new DataRelation("PO", _table.Columns["Id"], tableC.Columns["Id"], false); tableC.ParentRelations.Add(dr); rowC.SetParentRow(_table.Rows[0]); Assert.Equal(_table.Rows[0], (tableC.Rows[0]).GetParentRow(dr)); Assert.Equal(tableC.Rows[0], (_table.Rows[0]).GetChildRows(dr)[0]); } [Fact] public void ParentRowTest2() { var ds = new DataSet(); DataTable tableP = ds.Tables.Add("Parent"); DataTable tableC = ds.Tables.Add("Child"); DataColumn colC; DataRow rowC; colC = new DataColumn(); colC.DataType = typeof(int); colC.ColumnName = "Id"; colC.AutoIncrement = true; tableP.Columns.Add(colC); colC = new DataColumn(); colC.DataType = typeof(int); colC.ColumnName = "Id"; tableC.Columns.Add(colC); _row = tableP.Rows.Add(new object[0]); rowC = tableC.NewRow(); ds.EnforceConstraints = false; DataRelation dr = new DataRelation("PO", tableP.Columns["Id"], tableC.Columns["Id"]); ds.Relations.Add(dr); rowC.SetParentRow(_row, dr); DataRow[] rows = rowC.GetParentRows(dr); Assert.Equal(1, rows.Length); Assert.Equal(tableP.Rows[0], rows[0]); Assert.Throws<InvalidConstraintException>(() => _row.GetParentRows(dr)); } [Fact] public void ChildRowTest() { //Clear all existing values from table for (int i = 0; i < _table.Rows.Count; i++) { _table.Rows[i].Delete(); } _table.AcceptChanges(); _row = _table.NewRow(); _row["FName"] = "My FName"; _row["Id"] = 0; _table.Rows.Add(_row); DataTable tableC = new DataTable("Child"); DataColumn colC; DataRow rowC; colC = new DataColumn(); colC.DataType = typeof(int); colC.ColumnName = "Id"; colC.AutoIncrement = true; tableC.Columns.Add(colC); colC = new DataColumn(); colC.DataType = typeof(string); colC.ColumnName = "Name"; tableC.Columns.Add(colC); rowC = tableC.NewRow(); rowC["Name"] = "My FName"; tableC.Rows.Add(rowC); var ds = new DataSet(); ds.Tables.Add(_table); ds.Tables.Add(tableC); DataRelation dr = new DataRelation("PO", _table.Columns["Id"], tableC.Columns["Id"]); ds.Relations.Add(dr); rowC.SetParentRow(_table.Rows[0], dr); DataRow[] rows = (_table.Rows[0]).GetChildRows(dr); Assert.Equal(1, rows.Length); Assert.Equal(tableC.Rows[0], rows[0]); } [Fact] public void ChildRowTest2() { var ds = new DataSet(); DataTable tableP = ds.Tables.Add("Parent"); DataTable tableC = ds.Tables.Add("Child"); DataColumn colC; DataRow rowC; colC = new DataColumn(); colC.DataType = typeof(System.Int32); colC.ColumnName = "Id"; colC.AutoIncrement = true; tableP.Columns.Add(colC); colC = new DataColumn(); colC.DataType = typeof(System.Int32); colC.ColumnName = "Id"; tableC.Columns.Add(colC); _row = tableP.NewRow(); rowC = tableC.Rows.Add(new object[0]); ds.EnforceConstraints = false; DataRelation dr = new DataRelation("PO", tableP.Columns["Id"], tableC.Columns["Id"]); ds.Relations.Add(dr); rowC.SetParentRow(_row, dr); DataRow[] rows = _row.GetChildRows(dr); Assert.Equal(1, rows.Length); Assert.Equal(tableC.Rows[0], rows[0]); Assert.Throws<InvalidConstraintException>(() => rowC.GetChildRows(dr)); } // tests item at row, column in table to be DBNull.Value private void DBNullTest(string message, DataTable dt, int row, int column) { object val = dt.Rows[row].ItemArray[column]; Assert.Equal(DBNull.Value, val); } // tests item at row, column in table to be null private void NullTest(string message, DataTable dt, int row, int column) { object val = dt.Rows[row].ItemArray[column]; Assert.Null(val); } // tests item at row, column in table to be private void ValueTest(string message, DataTable dt, int row, int column, object value) { object val = dt.Rows[row].ItemArray[column]; Assert.Equal(value, val); } // test set null, DBNull.Value, and ItemArray short count [Fact] public void NullInItemArray() { string zero = "zero"; string one = "one"; string two = "two"; DataTable table = new DataTable(); table.Columns.Add(new DataColumn(zero, typeof(string))); table.Columns.Add(new DataColumn(one, typeof(string))); table.Columns.Add(new DataColumn(two, typeof(string))); object[] obj = new object[3]; // -- normal ----------------- obj[0] = zero; obj[1] = one; obj[2] = two; // results: // table.Rows[0].ItemArray.ItemArray[0] = "zero" // table.Rows[0].ItemArray.ItemArray[1] = "one" // table.Rows[0].ItemArray.ItemArray[2] = "two" DataRow row = table.NewRow(); row.ItemArray = obj; table.Rows.Add(row); // -- null ---------- obj[1] = null; // results: // table.Rows[1].ItemArray.ItemArray[0] = "zero" // table.Rows[1].ItemArray.ItemArray[1] = DBNull.Value // table.Rows[1].ItemArray.ItemArray[2] = "two" row = table.NewRow(); row.ItemArray = obj; table.Rows.Add(row); // -- DBNull.Value ------------- obj[1] = DBNull.Value; // results: // table.Rows[2].ItemArray.ItemArray[0] = "zero" // table.Rows[2].ItemArray.ItemArray[1] = DBNull.Value // table.Rows[2].ItemArray.ItemArray[2] = "two" row = table.NewRow(); row.ItemArray = obj; table.Rows.Add(row); // -- object array smaller than number of columns ----- string abc = "abc"; string def = "def"; obj = new object[2]; obj[0] = abc; obj[1] = def; // results: // table.Rows[3].ItemArray.ItemArray[0] = "abc" // table.Rows[3].ItemArray.ItemArray[1] = "def" // table.Rows[3].ItemArray.ItemArray[2] = DBNull.Value; row = table.NewRow(); row.ItemArray = obj; table.Rows.Add(row); // -- normal ----------------- ValueTest("DR5: normal value test", table, 0, 0, zero); ValueTest("DR6: normal value test", table, 0, 1, one); ValueTest("DR7: normal value test", table, 0, 2, two); // -- null ---------- ValueTest("DR8: null value test", table, 1, 0, zero); ValueTest("DR9: null value test", table, 1, 1, DBNull.Value); ValueTest("DR10: null value test", table, 1, 2, two); // -- DBNull.Value ------------- ValueTest("DR11: DBNull.Value value test", table, 2, 0, zero); ValueTest("DR12: DBNull.Value value test", table, 2, 1, DBNull.Value); ValueTest("DR13: DBNull.Value value test", table, 2, 2, two); // -- object array smaller than number of columns ----- ValueTest("DR14: array smaller value test", table, 3, 0, abc); ValueTest("DR15: array smaller value test", table, 3, 1, def); ValueTest("DR16: array smaller value test", table, 3, 2, DBNull.Value); } // test DefaultValue when setting ItemArray [Fact] public void DefaultValueInItemArray() { string zero = "zero"; DataTable table = new DataTable(); table.Columns.Add(new DataColumn("zero", typeof(string))); DataColumn column = new DataColumn("num", typeof(int)); column.DefaultValue = 15; table.Columns.Add(column); object[] obj = new object[2]; // -- normal ----------------- obj[0] = "zero"; obj[1] = 8; // results: // table.Rows[0].ItemArray.ItemArray[0] = "zero" // table.Rows[0].ItemArray.ItemArray[1] = 8 DataRow row = table.NewRow(); row.ItemArray = obj; table.Rows.Add(row); // -- null ---------- obj[1] = null; // results: // table.Rows[1].ItemArray.ItemArray[0] = "zero" // table.Rows[1].ItemArray.ItemArray[1] = 15 row = table.NewRow(); row.ItemArray = obj; table.Rows.Add(row); // -- DBNull.Value ------------- obj[1] = DBNull.Value; // results: // table.Rows[2].ItemArray.ItemArray[0] = "zero" // table.Rows[2].ItemArray.ItemArray[1] = DBNull.Value // even though internally, the v row = table.NewRow(); row.ItemArray = obj; table.Rows.Add(row); // -- object array smaller than number of columns ----- string abc = "abc"; string def = "def"; obj = new object[2]; obj[0] = abc; // results: // table.Rows[3].ItemArray.ItemArray[0] = "abc" // table.Rows[3].ItemArray.ItemArray[1] = DBNull.Value row = table.NewRow(); row.ItemArray = obj; table.Rows.Add(row); // -- normal ----------------- ValueTest("DR20: normal value test", table, 0, 0, zero); ValueTest("DR21: normal value test", table, 0, 1, 8); // -- null ---------- ValueTest("DR22: null value test", table, 1, 0, zero); ValueTest("DR23: null value test", table, 1, 1, 15); // -- DBNull.Value ------------- ValueTest("DR24: DBNull.Value value test", table, 2, 0, zero); DBNullTest("DR25: DBNull.Value value test", table, 2, 1); // -- object array smaller than number of columns ----- ValueTest("DR26: array smaller value test", table, 3, 0, abc); ValueTest("DR27: array smaller value test", table, 3, 1, 15); } // test AutoIncrement when setting ItemArray [Fact] public void AutoIncrementInItemArray() { string zero = "zero"; DataTable table = new DataTable(); table.Columns.Add(new DataColumn(zero, typeof(string))); DataColumn column = new DataColumn("num", typeof(int)); column.AutoIncrement = true; table.Columns.Add(column); object[] obj = new object[2]; // -- normal ----------------- obj[0] = "zero"; obj[1] = 8; // results: // table.Rows[0].ItemArray.ItemArray[0] = "zero" // table.Rows[0].ItemArray.ItemArray[1] = 8 DataRow row = table.NewRow(); row.ItemArray = obj; table.Rows.Add(row); // -- null 1---------- obj[1] = null; // results: // table.Rows[1].ItemArray.ItemArray[0] = "zero" // table.Rows[1].ItemArray.ItemArray[1] = 9 row = table.NewRow(); row.ItemArray = obj; table.Rows.Add(row); // -- null 2---------- obj[1] = null; // results: // table.Rows[1].ItemArray.ItemArray[0] = "zero" // table.Rows[1].ItemArray.ItemArray[1] = 10 row = table.NewRow(); row.ItemArray = obj; table.Rows.Add(row); // -- null 3---------- obj[1] = null; // results: // table.Rows[1].ItemArray.ItemArray[0] = "zero" // table.Rows[1].ItemArray.ItemArray[1] = 11 row = table.NewRow(); row.ItemArray = obj; table.Rows.Add(row); // -- DBNull.Value ------------- obj[1] = DBNull.Value; // results: // table.Rows[2].ItemArray.ItemArray[0] = "zero" // table.Rows[2].ItemArray.ItemArray[1] = DBNull.Value // even though internally, the AutoIncrement value // is incremented row = table.NewRow(); row.ItemArray = obj; table.Rows.Add(row); // -- null 4---------- obj[1] = null; // results: // table.Rows[1].ItemArray.ItemArray[0] = "zero" // table.Rows[1].ItemArray.ItemArray[1] = 13 row = table.NewRow(); row.ItemArray = obj; table.Rows.Add(row); // -- object array smaller than number of columns ----- string abc = "abc"; obj = new object[2]; obj[0] = abc; // results: // table.Rows[3].ItemArray.ItemArray[0] = "abc" // table.Rows[3].ItemArray.ItemArray[1] = 14 row = table.NewRow(); row.ItemArray = obj; table.Rows.Add(row); // -- normal ----------------- ValueTest("DR34: normal value test", table, 0, 0, zero); ValueTest("DR35: normal value test", table, 0, 1, 8); // -- null 1---------- ValueTest("DR36: null value test", table, 1, 0, zero); ValueTest("DR37: null value test", table, 1, 1, 9); // -- null 2---------- ValueTest("DR38: null value test", table, 2, 0, zero); ValueTest("DR39: null value test", table, 2, 1, 10); // -- null 3---------- ValueTest("DR40: null value test", table, 3, 0, zero); ValueTest("DR41: null value test", table, 3, 1, 11); // -- DBNull.Value ------------- ValueTest("DR42: DBNull.Value value test", table, 4, 0, zero); ValueTest("DR43: DBNull.Value value test", table, 4, 1, DBNull.Value); // -- null 4---------- ValueTest("DR44: null value test", table, 5, 0, zero); ValueTest("DR45: null value test", table, 5, 1, 13); // -- object array smaller than number of columns ----- ValueTest("DR46: array smaller value test", table, 6, 0, abc); ValueTest("DR47: array smaller value test", table, 6, 1, 14); } [Fact] public void AutoIncrementColumnIntegrity() { // AutoIncrement-column shouldn't raise index out of range // exception because of size mismatch of internal itemarray. DataTable dt = new DataTable(); dt.Columns.Add("foo"); dt.Rows.Add(new object[] { "value" }); DataColumn col = new DataColumn("bar"); col.AutoIncrement = true; dt.Columns.Add(col); dt.Rows[0][0] = "test"; } [Fact] public void EnforceConstraint() { int id = 100; // Setup stuff var ds = new DataSet(); DataTable parent = ds.Tables.Add("parent"); parent.Columns.Add("id", typeof(int)); DataTable child = ds.Tables.Add("child"); child.Columns.Add("idref", typeof(int)); Constraint uniqueId = new UniqueConstraint("uniqueId", new DataColumn[] { parent.Columns["id"] }, true); parent.Constraints.Add(uniqueId); ForeignKeyConstraint fkc = new ForeignKeyConstraint("ParentChildConstraint", new DataColumn[] { parent.Columns["id"] }, new DataColumn[] { child.Columns["idref"] }); child.Constraints.Add(fkc); DataRelation relateParentChild = new DataRelation("relateParentChild", new DataColumn[] { parent.Columns["id"] }, new DataColumn[] { child.Columns["idref"] }, false); ds.Relations.Add(relateParentChild); ds.EnforceConstraints = false; DataRow parentRow = parent.Rows.Add(new object[] { id }); DataRow childRow = child.Rows.Add(new object[] { id }); if (parentRow == childRow.GetParentRow(relateParentChild)) { foreach (DataColumn dc in parent.Columns) Assert.Equal(100, parentRow[dc]); } } [Fact] public void DetachedRowItemException() { Assert.Throws<RowNotInTableException>(() => { DataTable dt = new DataTable("table"); dt.Columns.Add("col"); dt.Rows.Add((new object[] { "val" })); DataRow dr = dt.NewRow(); Assert.Equal(DataRowState.Detached, dr.RowState); dr.CancelEdit(); Assert.Equal(DataRowState.Detached, dr.RowState); object o = dr["col"]; }); } [Fact] public void SetParentRow_Null() { var ds = new DataSet(); DataTable child = ds.Tables.Add("child"); child.Columns.Add("column1"); DataRow r1 = child.NewRow(); r1.SetParentRow(null); } [Fact] public void SetParentRow_DataInheritance() { var ds = new DataSet(); var child = ds.Tables.Add("child"); var childColumn1 = child.Columns.Add("column1"); var childColumn2 = child.Columns.Add("column2"); var parent1 = ds.Tables.Add("parent1"); var parent1Column1 = parent1.Columns.Add("column1"); var parent1Column2 = parent1.Columns.Add("column2"); var parent2 = ds.Tables.Add("parent2"); var parent2Column1 = parent2.Columns.Add("column1"); var parent2Column2 = parent2.Columns.Add("column2"); ds.Relations.Add("parent1-child", parent1Column1, childColumn1); ds.Relations.Add("parent2-child", parent2Column2, childColumn2); var childRow1 = child.NewRow(); var parent1Row = parent1.NewRow(); var parent2Row = parent2.NewRow(); parent1Row[parent1Column1] = "p1c1"; parent1Row[parent1Column2] = "p1c2"; parent2Row[parent2Column1] = "p2c1"; parent2Row[parent2Column2] = "p2c2"; child.Rows.Add(childRow1); parent1.Rows.Add(parent1Row); parent2.Rows.Add(parent2Row); childRow1.SetParentRow(parent1Row); Assert.Equal("p1c1", childRow1[childColumn1]); Assert.Equal(DBNull.Value, childRow1[childColumn2]); childRow1.SetParentRow(parent2Row); Assert.Equal("p1c1", childRow1[childColumn1]); Assert.Equal("p2c2", childRow1[childColumn2]); childRow1.SetParentRow(null); Assert.Equal(DBNull.Value, childRow1[childColumn1]); Assert.Equal(DBNull.Value, childRow1[childColumn2]); childRow1.SetParentRow(parent2Row); Assert.Equal(DBNull.Value, childRow1[childColumn1]); Assert.Equal("p2c2", childRow1[childColumn2]); } [Fact] public void SetParentRow_with_Relation() { var ds = new DataSet(); var child = ds.Tables.Add("child"); var childColumn1 = child.Columns.Add("column1"); var childColumn2 = child.Columns.Add("column2"); var parent1 = ds.Tables.Add("parent1"); var parent1Column1 = parent1.Columns.Add("column1"); var parent1Column2 = parent1.Columns.Add("column2"); var parent2 = ds.Tables.Add("parent2"); var parent2Column1 = parent2.Columns.Add("column1"); var parent2Column2 = parent2.Columns.Add("column2"); var relation1 = ds.Relations.Add("parent1-child", parent1Column1, childColumn1); var relation2 = ds.Relations.Add("parent2-child", parent2Column2, childColumn2); var childRow1 = child.NewRow(); var parent1Row = parent1.NewRow(); var parent2Row = parent2.NewRow(); parent1Row[parent1Column1] = "p1c1"; parent1Row[parent1Column2] = "p1c2"; parent2Row[parent2Column1] = "p2c1"; parent2Row[parent2Column2] = "p2c2"; child.Rows.Add(childRow1); parent1.Rows.Add(parent1Row); parent2.Rows.Add(parent2Row); childRow1.SetParentRow(null, relation2); Assert.Equal(DBNull.Value, childRow1[childColumn1]); Assert.Equal(DBNull.Value, childRow1[childColumn2]); Assert.Throws<InvalidConstraintException>(() => childRow1.SetParentRow(parent1Row, relation2)); Assert.Equal(DBNull.Value, childRow1[childColumn1]); Assert.Equal(DBNull.Value, childRow1[childColumn2]); childRow1.SetParentRow(parent1Row, relation1); Assert.Equal("p1c1", childRow1[childColumn1]); Assert.Equal(DBNull.Value, childRow1[childColumn2]); childRow1.SetParentRow(null, relation2); Assert.Equal("p1c1", childRow1[childColumn1]); Assert.Equal(DBNull.Value, childRow1[childColumn2]); childRow1.SetParentRow(null, relation1); Assert.Equal(DBNull.Value, childRow1[childColumn1]); Assert.Equal(DBNull.Value, childRow1[childColumn2]); } [Fact] public void SetParent_missing_ParentRow() { var ds = new DataSet(); var child = ds.Tables.Add("child"); var childColumn1 = child.Columns.Add("column1"); var childColumn2 = child.Columns.Add("column2"); var parent1 = ds.Tables.Add("parent1"); var parentColumn1 = parent1.Columns.Add("column1"); var parent2 = ds.Tables.Add("parent2"); var parentColumn2 = parent2.Columns.Add("column2"); ds.Relations.Add("parent1-child", parentColumn1, childColumn1); ds.Relations.Add("parent2-child", parentColumn2, childColumn2); var childRow = child.NewRow(); var parentRow = parent2.NewRow(); parentRow[parentColumn2] = "value"; child.Rows.Add(childRow); parent2.Rows.Add(parentRow); childRow.SetParentRow(parentRow); Assert.Equal(DBNull.Value, childRow[childColumn1]); Assert.Equal("value", childRow[childColumn2]); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // (C) Copyright 2002 Franklin Wise // (C) Copyright 2003 Daniel Morgan // (C) Copyright 2003 Martin Willemoes Hansen // // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using Xunit; namespace System.Data.Tests { public class DataRowTest { private DataTable _table; private DataRow _row; public DataRowTest() { _table = MakeTable(); _row = _table.NewRow(); _row["FName"] = "Hello"; _row["LName"] = "World"; _table.Rows.Add(_row); } private DataTable MakeTable() { DataTable namesTable = new DataTable("Names"); DataColumn idColumn = new DataColumn(); idColumn.DataType = typeof(int); idColumn.ColumnName = "Id"; idColumn.AutoIncrement = true; namesTable.Columns.Add(idColumn); DataColumn fNameColumn = new DataColumn(); fNameColumn.DataType = typeof(string); fNameColumn.ColumnName = "Fname"; fNameColumn.DefaultValue = "Fname"; namesTable.Columns.Add(fNameColumn); DataColumn lNameColumn = new DataColumn(); lNameColumn.DataType = typeof(string); lNameColumn.ColumnName = "LName"; lNameColumn.DefaultValue = "LName"; namesTable.Columns.Add(lNameColumn); // Set the primary key for the table DataColumn[] keys = new DataColumn[1]; keys[0] = idColumn; namesTable.PrimaryKey = keys; // Return the new DataTable. return namesTable; } [Fact] public void SetColumnErrorTest() { string errorString; errorString = "Some error!"; // Set the error for the specified column of the row. _row.SetColumnError(1, errorString); GetColumnErrorTest(); GetAllErrorsTest(); } private void GetColumnErrorTest() { // Print the error of a specified column. Assert.Equal("Some error!", _row.GetColumnError(1)); } private void GetAllErrorsTest() { DataColumn[] colArr; if (_row.HasErrors) { colArr = _row.GetColumnsInError(); for (int i = 0; i < colArr.Length; i++) { Assert.Same(_table.Columns[1], colArr[i]); } _row.ClearErrors(); } } [Fact] public void DeleteRowTest() { DataRow newRow; for (int i = 1; i <= 2; i++) { newRow = _table.NewRow(); newRow["FName"] = "Name " + i; newRow["LName"] = " Last Name" + i; _table.Rows.Add(newRow); } _table.AcceptChanges(); for (int i = 1; i < _table.Rows.Count; i++) { DataRow r = _table.Rows[i]; Assert.Equal("Name " + i, r["fName"]); } // Create a DataView with the table. DataRowCollection rc = _table.Rows; rc[0].Delete(); rc[2].Delete(); Assert.Equal("Deleted", rc[0].RowState.ToString()); Assert.Equal("Deleted", rc[2].RowState.ToString()); // Accept changes _table.AcceptChanges(); Assert.Equal("Name 1", (_table.Rows[0])[1]); // There is no row at position 2. Assert.Throws<IndexOutOfRangeException>(() => rc[2]); } [Fact] public void ParentRowTest() { //Clear all existing values from table for (int i = 0; i < _table.Rows.Count; i++) { _table.Rows[i].Delete(); } _table.AcceptChanges(); _row = _table.NewRow(); _row["FName"] = "My FName"; _row["Id"] = 0; _table.Rows.Add(_row); DataTable tableC = new DataTable("Child"); DataColumn colC; DataRow rowC; colC = new DataColumn(); colC.DataType = typeof(int); colC.ColumnName = "Id"; colC.AutoIncrement = true; tableC.Columns.Add(colC); colC = new DataColumn(); colC.DataType = typeof(string); colC.ColumnName = "Name"; tableC.Columns.Add(colC); rowC = tableC.NewRow(); rowC["Name"] = "My FName"; tableC.Rows.Add(rowC); var ds = new DataSet(); ds.Tables.Add(_table); ds.Tables.Add(tableC); DataRelation dr = new DataRelation("PO", _table.Columns["Id"], tableC.Columns["Id"]); ds.Relations.Add(dr); rowC.SetParentRow(_table.Rows[0], dr); Assert.Equal(_table.Rows[0], (tableC.Rows[0]).GetParentRow(dr)); Assert.Equal(tableC.Rows[0], (_table.Rows[0]).GetChildRows(dr)[0]); ds.Relations.Clear(); dr = new DataRelation("PO", _table.Columns["Id"], tableC.Columns["Id"], false); ds.Relations.Add(dr); rowC.SetParentRow(_table.Rows[0], dr); Assert.Equal(_table.Rows[0], (tableC.Rows[0]).GetParentRow(dr)); Assert.Equal(tableC.Rows[0], (_table.Rows[0]).GetChildRows(dr)[0]); ds.Relations.Clear(); dr = new DataRelation("PO", _table.Columns["Id"], tableC.Columns["Id"], false); tableC.ParentRelations.Add(dr); rowC.SetParentRow(_table.Rows[0]); Assert.Equal(_table.Rows[0], (tableC.Rows[0]).GetParentRow(dr)); Assert.Equal(tableC.Rows[0], (_table.Rows[0]).GetChildRows(dr)[0]); } [Fact] public void ParentRowTest2() { var ds = new DataSet(); DataTable tableP = ds.Tables.Add("Parent"); DataTable tableC = ds.Tables.Add("Child"); DataColumn colC; DataRow rowC; colC = new DataColumn(); colC.DataType = typeof(int); colC.ColumnName = "Id"; colC.AutoIncrement = true; tableP.Columns.Add(colC); colC = new DataColumn(); colC.DataType = typeof(int); colC.ColumnName = "Id"; tableC.Columns.Add(colC); _row = tableP.Rows.Add(new object[0]); rowC = tableC.NewRow(); ds.EnforceConstraints = false; DataRelation dr = new DataRelation("PO", tableP.Columns["Id"], tableC.Columns["Id"]); ds.Relations.Add(dr); rowC.SetParentRow(_row, dr); DataRow[] rows = rowC.GetParentRows(dr); Assert.Equal(1, rows.Length); Assert.Equal(tableP.Rows[0], rows[0]); Assert.Throws<InvalidConstraintException>(() => _row.GetParentRows(dr)); } [Fact] public void ChildRowTest() { //Clear all existing values from table for (int i = 0; i < _table.Rows.Count; i++) { _table.Rows[i].Delete(); } _table.AcceptChanges(); _row = _table.NewRow(); _row["FName"] = "My FName"; _row["Id"] = 0; _table.Rows.Add(_row); DataTable tableC = new DataTable("Child"); DataColumn colC; DataRow rowC; colC = new DataColumn(); colC.DataType = typeof(int); colC.ColumnName = "Id"; colC.AutoIncrement = true; tableC.Columns.Add(colC); colC = new DataColumn(); colC.DataType = typeof(string); colC.ColumnName = "Name"; tableC.Columns.Add(colC); rowC = tableC.NewRow(); rowC["Name"] = "My FName"; tableC.Rows.Add(rowC); var ds = new DataSet(); ds.Tables.Add(_table); ds.Tables.Add(tableC); DataRelation dr = new DataRelation("PO", _table.Columns["Id"], tableC.Columns["Id"]); ds.Relations.Add(dr); rowC.SetParentRow(_table.Rows[0], dr); DataRow[] rows = (_table.Rows[0]).GetChildRows(dr); Assert.Equal(1, rows.Length); Assert.Equal(tableC.Rows[0], rows[0]); } [Fact] public void ChildRowTest2() { var ds = new DataSet(); DataTable tableP = ds.Tables.Add("Parent"); DataTable tableC = ds.Tables.Add("Child"); DataColumn colC; DataRow rowC; colC = new DataColumn(); colC.DataType = typeof(System.Int32); colC.ColumnName = "Id"; colC.AutoIncrement = true; tableP.Columns.Add(colC); colC = new DataColumn(); colC.DataType = typeof(System.Int32); colC.ColumnName = "Id"; tableC.Columns.Add(colC); _row = tableP.NewRow(); rowC = tableC.Rows.Add(new object[0]); ds.EnforceConstraints = false; DataRelation dr = new DataRelation("PO", tableP.Columns["Id"], tableC.Columns["Id"]); ds.Relations.Add(dr); rowC.SetParentRow(_row, dr); DataRow[] rows = _row.GetChildRows(dr); Assert.Equal(1, rows.Length); Assert.Equal(tableC.Rows[0], rows[0]); Assert.Throws<InvalidConstraintException>(() => rowC.GetChildRows(dr)); } // tests item at row, column in table to be DBNull.Value private void DBNullTest(string message, DataTable dt, int row, int column) { object val = dt.Rows[row].ItemArray[column]; Assert.Equal(DBNull.Value, val); } // tests item at row, column in table to be null private void NullTest(string message, DataTable dt, int row, int column) { object val = dt.Rows[row].ItemArray[column]; Assert.Null(val); } // tests item at row, column in table to be private void ValueTest(string message, DataTable dt, int row, int column, object value) { object val = dt.Rows[row].ItemArray[column]; Assert.Equal(value, val); } // test set null, DBNull.Value, and ItemArray short count [Fact] public void NullInItemArray() { string zero = "zero"; string one = "one"; string two = "two"; DataTable table = new DataTable(); table.Columns.Add(new DataColumn(zero, typeof(string))); table.Columns.Add(new DataColumn(one, typeof(string))); table.Columns.Add(new DataColumn(two, typeof(string))); object[] obj = new object[3]; // -- normal ----------------- obj[0] = zero; obj[1] = one; obj[2] = two; // results: // table.Rows[0].ItemArray.ItemArray[0] = "zero" // table.Rows[0].ItemArray.ItemArray[1] = "one" // table.Rows[0].ItemArray.ItemArray[2] = "two" DataRow row = table.NewRow(); row.ItemArray = obj; table.Rows.Add(row); // -- null ---------- obj[1] = null; // results: // table.Rows[1].ItemArray.ItemArray[0] = "zero" // table.Rows[1].ItemArray.ItemArray[1] = DBNull.Value // table.Rows[1].ItemArray.ItemArray[2] = "two" row = table.NewRow(); row.ItemArray = obj; table.Rows.Add(row); // -- DBNull.Value ------------- obj[1] = DBNull.Value; // results: // table.Rows[2].ItemArray.ItemArray[0] = "zero" // table.Rows[2].ItemArray.ItemArray[1] = DBNull.Value // table.Rows[2].ItemArray.ItemArray[2] = "two" row = table.NewRow(); row.ItemArray = obj; table.Rows.Add(row); // -- object array smaller than number of columns ----- string abc = "abc"; string def = "def"; obj = new object[2]; obj[0] = abc; obj[1] = def; // results: // table.Rows[3].ItemArray.ItemArray[0] = "abc" // table.Rows[3].ItemArray.ItemArray[1] = "def" // table.Rows[3].ItemArray.ItemArray[2] = DBNull.Value; row = table.NewRow(); row.ItemArray = obj; table.Rows.Add(row); // -- normal ----------------- ValueTest("DR5: normal value test", table, 0, 0, zero); ValueTest("DR6: normal value test", table, 0, 1, one); ValueTest("DR7: normal value test", table, 0, 2, two); // -- null ---------- ValueTest("DR8: null value test", table, 1, 0, zero); ValueTest("DR9: null value test", table, 1, 1, DBNull.Value); ValueTest("DR10: null value test", table, 1, 2, two); // -- DBNull.Value ------------- ValueTest("DR11: DBNull.Value value test", table, 2, 0, zero); ValueTest("DR12: DBNull.Value value test", table, 2, 1, DBNull.Value); ValueTest("DR13: DBNull.Value value test", table, 2, 2, two); // -- object array smaller than number of columns ----- ValueTest("DR14: array smaller value test", table, 3, 0, abc); ValueTest("DR15: array smaller value test", table, 3, 1, def); ValueTest("DR16: array smaller value test", table, 3, 2, DBNull.Value); } // test DefaultValue when setting ItemArray [Fact] public void DefaultValueInItemArray() { string zero = "zero"; DataTable table = new DataTable(); table.Columns.Add(new DataColumn("zero", typeof(string))); DataColumn column = new DataColumn("num", typeof(int)); column.DefaultValue = 15; table.Columns.Add(column); object[] obj = new object[2]; // -- normal ----------------- obj[0] = "zero"; obj[1] = 8; // results: // table.Rows[0].ItemArray.ItemArray[0] = "zero" // table.Rows[0].ItemArray.ItemArray[1] = 8 DataRow row = table.NewRow(); row.ItemArray = obj; table.Rows.Add(row); // -- null ---------- obj[1] = null; // results: // table.Rows[1].ItemArray.ItemArray[0] = "zero" // table.Rows[1].ItemArray.ItemArray[1] = 15 row = table.NewRow(); row.ItemArray = obj; table.Rows.Add(row); // -- DBNull.Value ------------- obj[1] = DBNull.Value; // results: // table.Rows[2].ItemArray.ItemArray[0] = "zero" // table.Rows[2].ItemArray.ItemArray[1] = DBNull.Value // even though internally, the v row = table.NewRow(); row.ItemArray = obj; table.Rows.Add(row); // -- object array smaller than number of columns ----- string abc = "abc"; string def = "def"; obj = new object[2]; obj[0] = abc; // results: // table.Rows[3].ItemArray.ItemArray[0] = "abc" // table.Rows[3].ItemArray.ItemArray[1] = DBNull.Value row = table.NewRow(); row.ItemArray = obj; table.Rows.Add(row); // -- normal ----------------- ValueTest("DR20: normal value test", table, 0, 0, zero); ValueTest("DR21: normal value test", table, 0, 1, 8); // -- null ---------- ValueTest("DR22: null value test", table, 1, 0, zero); ValueTest("DR23: null value test", table, 1, 1, 15); // -- DBNull.Value ------------- ValueTest("DR24: DBNull.Value value test", table, 2, 0, zero); DBNullTest("DR25: DBNull.Value value test", table, 2, 1); // -- object array smaller than number of columns ----- ValueTest("DR26: array smaller value test", table, 3, 0, abc); ValueTest("DR27: array smaller value test", table, 3, 1, 15); } // test AutoIncrement when setting ItemArray [Fact] public void AutoIncrementInItemArray() { string zero = "zero"; DataTable table = new DataTable(); table.Columns.Add(new DataColumn(zero, typeof(string))); DataColumn column = new DataColumn("num", typeof(int)); column.AutoIncrement = true; table.Columns.Add(column); object[] obj = new object[2]; // -- normal ----------------- obj[0] = "zero"; obj[1] = 8; // results: // table.Rows[0].ItemArray.ItemArray[0] = "zero" // table.Rows[0].ItemArray.ItemArray[1] = 8 DataRow row = table.NewRow(); row.ItemArray = obj; table.Rows.Add(row); // -- null 1---------- obj[1] = null; // results: // table.Rows[1].ItemArray.ItemArray[0] = "zero" // table.Rows[1].ItemArray.ItemArray[1] = 9 row = table.NewRow(); row.ItemArray = obj; table.Rows.Add(row); // -- null 2---------- obj[1] = null; // results: // table.Rows[1].ItemArray.ItemArray[0] = "zero" // table.Rows[1].ItemArray.ItemArray[1] = 10 row = table.NewRow(); row.ItemArray = obj; table.Rows.Add(row); // -- null 3---------- obj[1] = null; // results: // table.Rows[1].ItemArray.ItemArray[0] = "zero" // table.Rows[1].ItemArray.ItemArray[1] = 11 row = table.NewRow(); row.ItemArray = obj; table.Rows.Add(row); // -- DBNull.Value ------------- obj[1] = DBNull.Value; // results: // table.Rows[2].ItemArray.ItemArray[0] = "zero" // table.Rows[2].ItemArray.ItemArray[1] = DBNull.Value // even though internally, the AutoIncrement value // is incremented row = table.NewRow(); row.ItemArray = obj; table.Rows.Add(row); // -- null 4---------- obj[1] = null; // results: // table.Rows[1].ItemArray.ItemArray[0] = "zero" // table.Rows[1].ItemArray.ItemArray[1] = 13 row = table.NewRow(); row.ItemArray = obj; table.Rows.Add(row); // -- object array smaller than number of columns ----- string abc = "abc"; obj = new object[2]; obj[0] = abc; // results: // table.Rows[3].ItemArray.ItemArray[0] = "abc" // table.Rows[3].ItemArray.ItemArray[1] = 14 row = table.NewRow(); row.ItemArray = obj; table.Rows.Add(row); // -- normal ----------------- ValueTest("DR34: normal value test", table, 0, 0, zero); ValueTest("DR35: normal value test", table, 0, 1, 8); // -- null 1---------- ValueTest("DR36: null value test", table, 1, 0, zero); ValueTest("DR37: null value test", table, 1, 1, 9); // -- null 2---------- ValueTest("DR38: null value test", table, 2, 0, zero); ValueTest("DR39: null value test", table, 2, 1, 10); // -- null 3---------- ValueTest("DR40: null value test", table, 3, 0, zero); ValueTest("DR41: null value test", table, 3, 1, 11); // -- DBNull.Value ------------- ValueTest("DR42: DBNull.Value value test", table, 4, 0, zero); ValueTest("DR43: DBNull.Value value test", table, 4, 1, DBNull.Value); // -- null 4---------- ValueTest("DR44: null value test", table, 5, 0, zero); ValueTest("DR45: null value test", table, 5, 1, 13); // -- object array smaller than number of columns ----- ValueTest("DR46: array smaller value test", table, 6, 0, abc); ValueTest("DR47: array smaller value test", table, 6, 1, 14); } [Fact] public void AutoIncrementColumnIntegrity() { // AutoIncrement-column shouldn't raise index out of range // exception because of size mismatch of internal itemarray. DataTable dt = new DataTable(); dt.Columns.Add("foo"); dt.Rows.Add(new object[] { "value" }); DataColumn col = new DataColumn("bar"); col.AutoIncrement = true; dt.Columns.Add(col); dt.Rows[0][0] = "test"; } [Fact] public void EnforceConstraint() { int id = 100; // Setup stuff var ds = new DataSet(); DataTable parent = ds.Tables.Add("parent"); parent.Columns.Add("id", typeof(int)); DataTable child = ds.Tables.Add("child"); child.Columns.Add("idref", typeof(int)); Constraint uniqueId = new UniqueConstraint("uniqueId", new DataColumn[] { parent.Columns["id"] }, true); parent.Constraints.Add(uniqueId); ForeignKeyConstraint fkc = new ForeignKeyConstraint("ParentChildConstraint", new DataColumn[] { parent.Columns["id"] }, new DataColumn[] { child.Columns["idref"] }); child.Constraints.Add(fkc); DataRelation relateParentChild = new DataRelation("relateParentChild", new DataColumn[] { parent.Columns["id"] }, new DataColumn[] { child.Columns["idref"] }, false); ds.Relations.Add(relateParentChild); ds.EnforceConstraints = false; DataRow parentRow = parent.Rows.Add(new object[] { id }); DataRow childRow = child.Rows.Add(new object[] { id }); if (parentRow == childRow.GetParentRow(relateParentChild)) { foreach (DataColumn dc in parent.Columns) Assert.Equal(100, parentRow[dc]); } } [Fact] public void DetachedRowItemException() { Assert.Throws<RowNotInTableException>(() => { DataTable dt = new DataTable("table"); dt.Columns.Add("col"); dt.Rows.Add((new object[] { "val" })); DataRow dr = dt.NewRow(); Assert.Equal(DataRowState.Detached, dr.RowState); dr.CancelEdit(); Assert.Equal(DataRowState.Detached, dr.RowState); object o = dr["col"]; }); } [Fact] public void SetParentRow_Null() { var ds = new DataSet(); DataTable child = ds.Tables.Add("child"); child.Columns.Add("column1"); DataRow r1 = child.NewRow(); r1.SetParentRow(null); } [Fact] public void SetParentRow_DataInheritance() { var ds = new DataSet(); var child = ds.Tables.Add("child"); var childColumn1 = child.Columns.Add("column1"); var childColumn2 = child.Columns.Add("column2"); var parent1 = ds.Tables.Add("parent1"); var parent1Column1 = parent1.Columns.Add("column1"); var parent1Column2 = parent1.Columns.Add("column2"); var parent2 = ds.Tables.Add("parent2"); var parent2Column1 = parent2.Columns.Add("column1"); var parent2Column2 = parent2.Columns.Add("column2"); ds.Relations.Add("parent1-child", parent1Column1, childColumn1); ds.Relations.Add("parent2-child", parent2Column2, childColumn2); var childRow1 = child.NewRow(); var parent1Row = parent1.NewRow(); var parent2Row = parent2.NewRow(); parent1Row[parent1Column1] = "p1c1"; parent1Row[parent1Column2] = "p1c2"; parent2Row[parent2Column1] = "p2c1"; parent2Row[parent2Column2] = "p2c2"; child.Rows.Add(childRow1); parent1.Rows.Add(parent1Row); parent2.Rows.Add(parent2Row); childRow1.SetParentRow(parent1Row); Assert.Equal("p1c1", childRow1[childColumn1]); Assert.Equal(DBNull.Value, childRow1[childColumn2]); childRow1.SetParentRow(parent2Row); Assert.Equal("p1c1", childRow1[childColumn1]); Assert.Equal("p2c2", childRow1[childColumn2]); childRow1.SetParentRow(null); Assert.Equal(DBNull.Value, childRow1[childColumn1]); Assert.Equal(DBNull.Value, childRow1[childColumn2]); childRow1.SetParentRow(parent2Row); Assert.Equal(DBNull.Value, childRow1[childColumn1]); Assert.Equal("p2c2", childRow1[childColumn2]); } [Fact] public void SetParentRow_with_Relation() { var ds = new DataSet(); var child = ds.Tables.Add("child"); var childColumn1 = child.Columns.Add("column1"); var childColumn2 = child.Columns.Add("column2"); var parent1 = ds.Tables.Add("parent1"); var parent1Column1 = parent1.Columns.Add("column1"); var parent1Column2 = parent1.Columns.Add("column2"); var parent2 = ds.Tables.Add("parent2"); var parent2Column1 = parent2.Columns.Add("column1"); var parent2Column2 = parent2.Columns.Add("column2"); var relation1 = ds.Relations.Add("parent1-child", parent1Column1, childColumn1); var relation2 = ds.Relations.Add("parent2-child", parent2Column2, childColumn2); var childRow1 = child.NewRow(); var parent1Row = parent1.NewRow(); var parent2Row = parent2.NewRow(); parent1Row[parent1Column1] = "p1c1"; parent1Row[parent1Column2] = "p1c2"; parent2Row[parent2Column1] = "p2c1"; parent2Row[parent2Column2] = "p2c2"; child.Rows.Add(childRow1); parent1.Rows.Add(parent1Row); parent2.Rows.Add(parent2Row); childRow1.SetParentRow(null, relation2); Assert.Equal(DBNull.Value, childRow1[childColumn1]); Assert.Equal(DBNull.Value, childRow1[childColumn2]); Assert.Throws<InvalidConstraintException>(() => childRow1.SetParentRow(parent1Row, relation2)); Assert.Equal(DBNull.Value, childRow1[childColumn1]); Assert.Equal(DBNull.Value, childRow1[childColumn2]); childRow1.SetParentRow(parent1Row, relation1); Assert.Equal("p1c1", childRow1[childColumn1]); Assert.Equal(DBNull.Value, childRow1[childColumn2]); childRow1.SetParentRow(null, relation2); Assert.Equal("p1c1", childRow1[childColumn1]); Assert.Equal(DBNull.Value, childRow1[childColumn2]); childRow1.SetParentRow(null, relation1); Assert.Equal(DBNull.Value, childRow1[childColumn1]); Assert.Equal(DBNull.Value, childRow1[childColumn2]); } [Fact] public void SetParent_missing_ParentRow() { var ds = new DataSet(); var child = ds.Tables.Add("child"); var childColumn1 = child.Columns.Add("column1"); var childColumn2 = child.Columns.Add("column2"); var parent1 = ds.Tables.Add("parent1"); var parentColumn1 = parent1.Columns.Add("column1"); var parent2 = ds.Tables.Add("parent2"); var parentColumn2 = parent2.Columns.Add("column2"); ds.Relations.Add("parent1-child", parentColumn1, childColumn1); ds.Relations.Add("parent2-child", parentColumn2, childColumn2); var childRow = child.NewRow(); var parentRow = parent2.NewRow(); parentRow[parentColumn2] = "value"; child.Rows.Add(childRow); parent2.Rows.Add(parentRow); childRow.SetParentRow(parentRow); Assert.Equal(DBNull.Value, childRow[childColumn1]); Assert.Equal("value", childRow[childColumn2]); } } }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/tests/Interop/PInvoke/Array/MarshalArrayAsParam/LPArrayNative/CMakeLists.txt
project (MarshalArrayLPArrayNative) include ("${CLR_INTEROP_TEST_ROOT}/Interop.cmake") include_directories("../..") set(SOURCES MarshalArrayLPArrayNative.cpp ) # add the executable add_library (MarshalArrayLPArrayNative SHARED ${SOURCES}) target_link_libraries(MarshalArrayLPArrayNative ${LINK_LIBRARIES_ADDITIONAL}) # add the install targets install (TARGETS MarshalArrayLPArrayNative DESTINATION bin)
project (MarshalArrayLPArrayNative) include ("${CLR_INTEROP_TEST_ROOT}/Interop.cmake") include_directories("../..") set(SOURCES MarshalArrayLPArrayNative.cpp ) # add the executable add_library (MarshalArrayLPArrayNative SHARED ${SOURCES}) target_link_libraries(MarshalArrayLPArrayNative ${LINK_LIBRARIES_ADDITIONAL}) # add the install targets install (TARGETS MarshalArrayLPArrayNative DESTINATION bin)
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/libraries/Common/src/System/Net/SocketAddress.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers.Binary; using System.Diagnostics; using System.Globalization; using System.Net.Sockets; using System.Text; #if SYSTEM_NET_PRIMITIVES_DLL namespace System.Net #else namespace System.Net.Internals #endif { // This class is used when subclassing EndPoint, and provides indication // on how to format the memory buffers that the platform uses for network addresses. #if SYSTEM_NET_PRIMITIVES_DLL public #else internal #endif class SocketAddress { #pragma warning disable CA1802 // these could be const on Windows but need to be static readonly for Unix internal static readonly int IPv6AddressSize = SocketAddressPal.IPv6AddressSize; internal static readonly int IPv4AddressSize = SocketAddressPal.IPv4AddressSize; #pragma warning restore CA1802 internal int InternalSize; internal byte[] Buffer; private const int MinSize = 2; private const int MaxSize = 32; // IrDA requires 32 bytes private const int DataOffset = 2; private bool _changed = true; private int _hash; public AddressFamily Family { get { return SocketAddressPal.GetAddressFamily(Buffer); } } public int Size { get { return InternalSize; } } // Access to unmanaged serialized data. This doesn't // allow access to the first 2 bytes of unmanaged memory // that are supposed to contain the address family which // is readonly. public byte this[int offset] { get { if (offset < 0 || offset >= Size) { throw new IndexOutOfRangeException(); } return Buffer[offset]; } set { if (offset < 0 || offset >= Size) { throw new IndexOutOfRangeException(); } if (Buffer[offset] != value) { _changed = true; } Buffer[offset] = value; } } public SocketAddress(AddressFamily family) : this(family, MaxSize) { } public SocketAddress(AddressFamily family, int size) { if (size < MinSize) { throw new ArgumentOutOfRangeException(nameof(size)); } InternalSize = size; Buffer = new byte[(size / IntPtr.Size + 2) * IntPtr.Size]; SocketAddressPal.SetAddressFamily(Buffer, family); } internal SocketAddress(IPAddress ipAddress) : this(ipAddress.AddressFamily, ((ipAddress.AddressFamily == AddressFamily.InterNetwork) ? IPv4AddressSize : IPv6AddressSize)) { // No Port. SocketAddressPal.SetPort(Buffer, 0); if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6) { Span<byte> addressBytes = stackalloc byte[IPAddressParserStatics.IPv6AddressBytes]; ipAddress.TryWriteBytes(addressBytes, out int bytesWritten); Debug.Assert(bytesWritten == IPAddressParserStatics.IPv6AddressBytes); SocketAddressPal.SetIPv6Address(Buffer, addressBytes, (uint)ipAddress.ScopeId); } else { #pragma warning disable CS0618 // using Obsolete Address API because it's the more efficient option in this case uint address = unchecked((uint)ipAddress.Address); #pragma warning restore CS0618 Debug.Assert(ipAddress.AddressFamily == AddressFamily.InterNetwork); SocketAddressPal.SetIPv4Address(Buffer, address); } } internal SocketAddress(IPAddress ipaddress, int port) : this(ipaddress) { SocketAddressPal.SetPort(Buffer, unchecked((ushort)port)); } internal SocketAddress(AddressFamily addressFamily, ReadOnlySpan<byte> buffer) { Buffer = buffer.ToArray(); InternalSize = Buffer.Length; } internal IPAddress GetIPAddress() { if (Family == AddressFamily.InterNetworkV6) { Debug.Assert(Size >= IPv6AddressSize); Span<byte> address = stackalloc byte[IPAddressParserStatics.IPv6AddressBytes]; uint scope; SocketAddressPal.GetIPv6Address(Buffer, address, out scope); return new IPAddress(address, (long)scope); } else if (Family == AddressFamily.InterNetwork) { Debug.Assert(Size >= IPv4AddressSize); long address = (long)SocketAddressPal.GetIPv4Address(Buffer) & 0x0FFFFFFFF; return new IPAddress(address); } else { #if SYSTEM_NET_PRIMITIVES_DLL throw new SocketException(SocketError.AddressFamilyNotSupported); #else throw new SocketException((int)SocketError.AddressFamilyNotSupported); #endif } } internal IPEndPoint GetIPEndPoint() { IPAddress address = GetIPAddress(); int port = (int)SocketAddressPal.GetPort(Buffer); return new IPEndPoint(address, port); } // For ReceiveFrom we need to pin address size, using reserved Buffer space. internal void CopyAddressSizeIntoBuffer() { Buffer[Buffer.Length - IntPtr.Size] = unchecked((byte)(InternalSize)); Buffer[Buffer.Length - IntPtr.Size + 1] = unchecked((byte)(InternalSize >> 8)); Buffer[Buffer.Length - IntPtr.Size + 2] = unchecked((byte)(InternalSize >> 16)); Buffer[Buffer.Length - IntPtr.Size + 3] = unchecked((byte)(InternalSize >> 24)); } // Can be called after the above method did work. internal int GetAddressSizeOffset() { return Buffer.Length - IntPtr.Size; } public override bool Equals(object? comparand) { SocketAddress? castedComparand = comparand as SocketAddress; if (castedComparand == null || this.Size != castedComparand.Size) { return false; } for (int i = 0; i < this.Size; i++) { if (this[i] != castedComparand[i]) { return false; } } return true; } public override int GetHashCode() { if (_changed) { _changed = false; _hash = 0; int i; int size = Size & ~3; for (i = 0; i < size; i += 4) { _hash ^= BinaryPrimitives.ReadInt32LittleEndian(Buffer.AsSpan(i)); } if ((Size & 3) != 0) { int remnant = 0; int shift = 0; for (; i < Size; ++i) { remnant |= ((int)Buffer[i]) << shift; shift += 8; } _hash ^= remnant; } } return _hash; } public override string ToString() { // Get the address family string. In almost all cases, this should be a cached string // from the enum and won't actually allocate. string familyString = Family.ToString(); // Determine the maximum length needed to format. int maxLength = familyString.Length + // AddressFamily 1 + // : 10 + // Size (max length for a positive Int32) 2 + // :{ (Size - DataOffset) * 4 + // at most ','+3digits per byte 1; // } Span<char> result = maxLength <= 256 ? // arbitrary limit that should be large enough for the vast majority of cases stackalloc char[256] : new char[maxLength]; familyString.CopyTo(result); int length = familyString.Length; result[length++] = ':'; bool formatted = Size.TryFormat(result.Slice(length), out int charsWritten); Debug.Assert(formatted); length += charsWritten; result[length++] = ':'; result[length++] = '{'; byte[] buffer = Buffer; for (int i = DataOffset; i < Size; i++) { if (i > DataOffset) { result[length++] = ','; } formatted = buffer[i].TryFormat(result.Slice(length), out charsWritten); Debug.Assert(formatted); length += charsWritten; } result[length++] = '}'; return result.Slice(0, length).ToString(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers.Binary; using System.Diagnostics; using System.Globalization; using System.Net.Sockets; using System.Text; #if SYSTEM_NET_PRIMITIVES_DLL namespace System.Net #else namespace System.Net.Internals #endif { // This class is used when subclassing EndPoint, and provides indication // on how to format the memory buffers that the platform uses for network addresses. #if SYSTEM_NET_PRIMITIVES_DLL public #else internal #endif class SocketAddress { #pragma warning disable CA1802 // these could be const on Windows but need to be static readonly for Unix internal static readonly int IPv6AddressSize = SocketAddressPal.IPv6AddressSize; internal static readonly int IPv4AddressSize = SocketAddressPal.IPv4AddressSize; #pragma warning restore CA1802 internal int InternalSize; internal byte[] Buffer; private const int MinSize = 2; private const int MaxSize = 32; // IrDA requires 32 bytes private const int DataOffset = 2; private bool _changed = true; private int _hash; public AddressFamily Family { get { return SocketAddressPal.GetAddressFamily(Buffer); } } public int Size { get { return InternalSize; } } // Access to unmanaged serialized data. This doesn't // allow access to the first 2 bytes of unmanaged memory // that are supposed to contain the address family which // is readonly. public byte this[int offset] { get { if (offset < 0 || offset >= Size) { throw new IndexOutOfRangeException(); } return Buffer[offset]; } set { if (offset < 0 || offset >= Size) { throw new IndexOutOfRangeException(); } if (Buffer[offset] != value) { _changed = true; } Buffer[offset] = value; } } public SocketAddress(AddressFamily family) : this(family, MaxSize) { } public SocketAddress(AddressFamily family, int size) { if (size < MinSize) { throw new ArgumentOutOfRangeException(nameof(size)); } InternalSize = size; Buffer = new byte[(size / IntPtr.Size + 2) * IntPtr.Size]; SocketAddressPal.SetAddressFamily(Buffer, family); } internal SocketAddress(IPAddress ipAddress) : this(ipAddress.AddressFamily, ((ipAddress.AddressFamily == AddressFamily.InterNetwork) ? IPv4AddressSize : IPv6AddressSize)) { // No Port. SocketAddressPal.SetPort(Buffer, 0); if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6) { Span<byte> addressBytes = stackalloc byte[IPAddressParserStatics.IPv6AddressBytes]; ipAddress.TryWriteBytes(addressBytes, out int bytesWritten); Debug.Assert(bytesWritten == IPAddressParserStatics.IPv6AddressBytes); SocketAddressPal.SetIPv6Address(Buffer, addressBytes, (uint)ipAddress.ScopeId); } else { #pragma warning disable CS0618 // using Obsolete Address API because it's the more efficient option in this case uint address = unchecked((uint)ipAddress.Address); #pragma warning restore CS0618 Debug.Assert(ipAddress.AddressFamily == AddressFamily.InterNetwork); SocketAddressPal.SetIPv4Address(Buffer, address); } } internal SocketAddress(IPAddress ipaddress, int port) : this(ipaddress) { SocketAddressPal.SetPort(Buffer, unchecked((ushort)port)); } internal SocketAddress(AddressFamily addressFamily, ReadOnlySpan<byte> buffer) { Buffer = buffer.ToArray(); InternalSize = Buffer.Length; } internal IPAddress GetIPAddress() { if (Family == AddressFamily.InterNetworkV6) { Debug.Assert(Size >= IPv6AddressSize); Span<byte> address = stackalloc byte[IPAddressParserStatics.IPv6AddressBytes]; uint scope; SocketAddressPal.GetIPv6Address(Buffer, address, out scope); return new IPAddress(address, (long)scope); } else if (Family == AddressFamily.InterNetwork) { Debug.Assert(Size >= IPv4AddressSize); long address = (long)SocketAddressPal.GetIPv4Address(Buffer) & 0x0FFFFFFFF; return new IPAddress(address); } else { #if SYSTEM_NET_PRIMITIVES_DLL throw new SocketException(SocketError.AddressFamilyNotSupported); #else throw new SocketException((int)SocketError.AddressFamilyNotSupported); #endif } } internal IPEndPoint GetIPEndPoint() { IPAddress address = GetIPAddress(); int port = (int)SocketAddressPal.GetPort(Buffer); return new IPEndPoint(address, port); } // For ReceiveFrom we need to pin address size, using reserved Buffer space. internal void CopyAddressSizeIntoBuffer() { Buffer[Buffer.Length - IntPtr.Size] = unchecked((byte)(InternalSize)); Buffer[Buffer.Length - IntPtr.Size + 1] = unchecked((byte)(InternalSize >> 8)); Buffer[Buffer.Length - IntPtr.Size + 2] = unchecked((byte)(InternalSize >> 16)); Buffer[Buffer.Length - IntPtr.Size + 3] = unchecked((byte)(InternalSize >> 24)); } // Can be called after the above method did work. internal int GetAddressSizeOffset() { return Buffer.Length - IntPtr.Size; } public override bool Equals(object? comparand) { SocketAddress? castedComparand = comparand as SocketAddress; if (castedComparand == null || this.Size != castedComparand.Size) { return false; } for (int i = 0; i < this.Size; i++) { if (this[i] != castedComparand[i]) { return false; } } return true; } public override int GetHashCode() { if (_changed) { _changed = false; _hash = 0; int i; int size = Size & ~3; for (i = 0; i < size; i += 4) { _hash ^= BinaryPrimitives.ReadInt32LittleEndian(Buffer.AsSpan(i)); } if ((Size & 3) != 0) { int remnant = 0; int shift = 0; for (; i < Size; ++i) { remnant |= ((int)Buffer[i]) << shift; shift += 8; } _hash ^= remnant; } } return _hash; } public override string ToString() { // Get the address family string. In almost all cases, this should be a cached string // from the enum and won't actually allocate. string familyString = Family.ToString(); // Determine the maximum length needed to format. int maxLength = familyString.Length + // AddressFamily 1 + // : 10 + // Size (max length for a positive Int32) 2 + // :{ (Size - DataOffset) * 4 + // at most ','+3digits per byte 1; // } Span<char> result = maxLength <= 256 ? // arbitrary limit that should be large enough for the vast majority of cases stackalloc char[256] : new char[maxLength]; familyString.CopyTo(result); int length = familyString.Length; result[length++] = ':'; bool formatted = Size.TryFormat(result.Slice(length), out int charsWritten); Debug.Assert(formatted); length += charsWritten; result[length++] = ':'; result[length++] = '{'; byte[] buffer = Buffer; for (int i = DataOffset; i < Size; i++) { if (i > DataOffset) { result[length++] = ','; } formatted = buffer[i].TryFormat(result.Slice(length), out charsWritten); Debug.Assert(formatted); length += charsWritten; } result[length++] = '}'; return result.Slice(0, length).ToString(); } } }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/ShiftLogicalSaturate.Vector128.Byte.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void ShiftLogicalSaturate_Vector128_Byte() { var test = new SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_Byte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_Byte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, SByte[] inArray2, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Byte> _fld1; public Vector128<SByte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_Byte testClass) { var result = AdvSimd.ShiftLogicalSaturate(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_Byte testClass) { fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = AdvSimd.ShiftLogicalSaturate( AdvSimd.LoadVector128((Byte*)(pFld1)), AdvSimd.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector128<Byte> _clsVar1; private static Vector128<SByte> _clsVar2; private Vector128<Byte> _fld1; private Vector128<SByte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_Byte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); } public SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_Byte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.ShiftLogicalSaturate( Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.ShiftLogicalSaturate( AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftLogicalSaturate), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftLogicalSaturate), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftLogicalSaturate( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Byte>* pClsVar1 = &_clsVar1) fixed (Vector128<SByte>* pClsVar2 = &_clsVar2) { var result = AdvSimd.ShiftLogicalSaturate( AdvSimd.LoadVector128((Byte*)(pClsVar1)), AdvSimd.LoadVector128((SByte*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr); var result = AdvSimd.ShiftLogicalSaturate(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr)); var result = AdvSimd.ShiftLogicalSaturate(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_Byte(); var result = AdvSimd.ShiftLogicalSaturate(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_Byte(); fixed (Vector128<Byte>* pFld1 = &test._fld1) fixed (Vector128<SByte>* pFld2 = &test._fld2) { var result = AdvSimd.ShiftLogicalSaturate( AdvSimd.LoadVector128((Byte*)(pFld1)), AdvSimd.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftLogicalSaturate(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = AdvSimd.ShiftLogicalSaturate( AdvSimd.LoadVector128((Byte*)(pFld1)), AdvSimd.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.ShiftLogicalSaturate(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.ShiftLogicalSaturate( AdvSimd.LoadVector128((Byte*)(&test._fld1)), AdvSimd.LoadVector128((SByte*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Byte> op1, Vector128<SByte> op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, SByte[] right, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftLogicalSaturate(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftLogicalSaturate)}<Byte>(Vector128<Byte>, Vector128<SByte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void ShiftLogicalSaturate_Vector128_Byte() { var test = new SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_Byte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_Byte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, SByte[] inArray2, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Byte> _fld1; public Vector128<SByte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_Byte testClass) { var result = AdvSimd.ShiftLogicalSaturate(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_Byte testClass) { fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = AdvSimd.ShiftLogicalSaturate( AdvSimd.LoadVector128((Byte*)(pFld1)), AdvSimd.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector128<Byte> _clsVar1; private static Vector128<SByte> _clsVar2; private Vector128<Byte> _fld1; private Vector128<SByte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_Byte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); } public SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_Byte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.ShiftLogicalSaturate( Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.ShiftLogicalSaturate( AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftLogicalSaturate), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftLogicalSaturate), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftLogicalSaturate( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Byte>* pClsVar1 = &_clsVar1) fixed (Vector128<SByte>* pClsVar2 = &_clsVar2) { var result = AdvSimd.ShiftLogicalSaturate( AdvSimd.LoadVector128((Byte*)(pClsVar1)), AdvSimd.LoadVector128((SByte*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr); var result = AdvSimd.ShiftLogicalSaturate(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr)); var result = AdvSimd.ShiftLogicalSaturate(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_Byte(); var result = AdvSimd.ShiftLogicalSaturate(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_Byte(); fixed (Vector128<Byte>* pFld1 = &test._fld1) fixed (Vector128<SByte>* pFld2 = &test._fld2) { var result = AdvSimd.ShiftLogicalSaturate( AdvSimd.LoadVector128((Byte*)(pFld1)), AdvSimd.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftLogicalSaturate(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = AdvSimd.ShiftLogicalSaturate( AdvSimd.LoadVector128((Byte*)(pFld1)), AdvSimd.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.ShiftLogicalSaturate(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.ShiftLogicalSaturate( AdvSimd.LoadVector128((Byte*)(&test._fld1)), AdvSimd.LoadVector128((SByte*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Byte> op1, Vector128<SByte> op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, SByte[] right, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftLogicalSaturate(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftLogicalSaturate)}<Byte>(Vector128<Byte>, Vector128<SByte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/RefreshPropertiesAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; namespace System.ComponentModel { /// <summary> /// Specifies how a designer refreshes when the property value is changed. /// </summary> [AttributeUsage(AttributeTargets.All)] public sealed class RefreshPropertiesAttribute : Attribute { /// <summary> /// Indicates all properties should be refreshed if the property value is changed. /// This field is read-only. /// </summary> public static readonly RefreshPropertiesAttribute All = new RefreshPropertiesAttribute(RefreshProperties.All); /// <summary> /// Indicates all properties should be invalidated and repainted if the property /// value is changed. This field is read-only. /// </summary> public static readonly RefreshPropertiesAttribute Repaint = new RefreshPropertiesAttribute(RefreshProperties.Repaint); /// <summary> /// Indicates that by default no properties should be refreshed if the property /// value is changed. This field is read-only. /// </summary> public static readonly RefreshPropertiesAttribute Default = new RefreshPropertiesAttribute(RefreshProperties.None); public RefreshPropertiesAttribute(RefreshProperties refresh) { RefreshProperties = refresh; } /// <summary> /// Gets the refresh properties for the member. /// </summary> public RefreshProperties RefreshProperties { get; } public override bool Equals([NotNullWhen(true)] object? obj) => obj is RefreshPropertiesAttribute other && other.RefreshProperties == RefreshProperties; public override int GetHashCode() => base.GetHashCode(); public override bool IsDefaultAttribute() => Equals(Default); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; namespace System.ComponentModel { /// <summary> /// Specifies how a designer refreshes when the property value is changed. /// </summary> [AttributeUsage(AttributeTargets.All)] public sealed class RefreshPropertiesAttribute : Attribute { /// <summary> /// Indicates all properties should be refreshed if the property value is changed. /// This field is read-only. /// </summary> public static readonly RefreshPropertiesAttribute All = new RefreshPropertiesAttribute(RefreshProperties.All); /// <summary> /// Indicates all properties should be invalidated and repainted if the property /// value is changed. This field is read-only. /// </summary> public static readonly RefreshPropertiesAttribute Repaint = new RefreshPropertiesAttribute(RefreshProperties.Repaint); /// <summary> /// Indicates that by default no properties should be refreshed if the property /// value is changed. This field is read-only. /// </summary> public static readonly RefreshPropertiesAttribute Default = new RefreshPropertiesAttribute(RefreshProperties.None); public RefreshPropertiesAttribute(RefreshProperties refresh) { RefreshProperties = refresh; } /// <summary> /// Gets the refresh properties for the member. /// </summary> public RefreshProperties RefreshProperties { get; } public override bool Equals([NotNullWhen(true)] object? obj) => obj is RefreshPropertiesAttribute other && other.RefreshProperties == RefreshProperties; public override int GetHashCode() => base.GetHashCode(); public override bool IsDefaultAttribute() => Equals(Default); } }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/tests/JIT/jit64/valuetypes/nullable/box-unbox/generics/box-unbox-generics016.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // <Area> Nullable - Box-Unbox </Area> // <Title> Nullable type with unbox box expr </Title> // <Description> // checking type of Guid using is operator // </Description> // <RelatedBugs> </RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Runtime.InteropServices; using System; internal class NullableTest { private static bool BoxUnboxToNQ<T>(T o) { return Helper.Compare((Guid)(object)o, Helper.Create(default(Guid))); } private static bool BoxUnboxToQ<T>(T o) { return Helper.Compare((Guid?)(object)o, Helper.Create(default(Guid))); } private static int Main() { Guid? s = Helper.Create(default(Guid)); if (BoxUnboxToNQ(s) && BoxUnboxToQ(s)) return ExitCode.Passed; else return ExitCode.Failed; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // <Area> Nullable - Box-Unbox </Area> // <Title> Nullable type with unbox box expr </Title> // <Description> // checking type of Guid using is operator // </Description> // <RelatedBugs> </RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Runtime.InteropServices; using System; internal class NullableTest { private static bool BoxUnboxToNQ<T>(T o) { return Helper.Compare((Guid)(object)o, Helper.Create(default(Guid))); } private static bool BoxUnboxToQ<T>(T o) { return Helper.Compare((Guid?)(object)o, Helper.Create(default(Guid))); } private static int Main() { Guid? s = Helper.Create(default(Guid)); if (BoxUnboxToNQ(s) && BoxUnboxToQ(s)) return ExitCode.Passed; else return ExitCode.Failed; } }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/libraries/System.ComponentModel.Composition.Registration/tests/System/ComponentModel/Composition/Registration/RegistrationContextUnitTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel.Composition.Hosting; using System.Linq; using Xunit; namespace System.ComponentModel.Composition.Registration.Tests { public interface IFoo { } public class FooImplementation1 : IFoo { } public class FooImplementation2 : IFoo { } public class RegistrationBuilderUnitTests { [Fact] public void UndecoratedContext_ShouldFindZeroParts() { var ctx = new RegistrationBuilder(); var catalog = new TypeCatalog(new[] { typeof(IFoo), typeof(FooImplementation1), typeof(FooImplementation2) }, ctx); Assert.True(catalog.Parts.Count() == 0); } [Fact] public void ImplementsIFooNoExport_ShouldFindZeroParts() { var ctx = new RegistrationBuilder(); ctx.ForTypesDerivedFrom<IFoo>(); var catalog = new TypeCatalog(new[] { typeof(IFoo), typeof(FooImplementation1), typeof(FooImplementation2) }, ctx); Assert.True(catalog.Parts.Count() == 0); } [Fact] public void ImplementsIFooWithExport_ShouldFindTwoParts() { var ctx = new RegistrationBuilder(); ctx.ForTypesDerivedFrom<IFoo>().Export(); var catalog = new TypeCatalog(new[] { typeof(IFoo), typeof(FooImplementation1), typeof(FooImplementation2) }, ctx); Assert.True(catalog.Parts.Count() == 2); } [Fact] public void OfTypeInterfaceNoExport_ShouldFindZeroParts() { var ctx = new RegistrationBuilder(); ctx.ForType<IFoo>(); var catalog = new TypeCatalog(new[] { typeof(IFoo), typeof(FooImplementation1), typeof(FooImplementation2) }, ctx); Assert.True(catalog.Parts.Count() == 0); } [Fact] public void OfTypeInterfaceWithExport_ShouldFindZeroParts() { var ctx = new RegistrationBuilder(); ctx.ForType<IFoo>().Export(); var catalog = new TypeCatalog(new[] { typeof(IFoo), typeof(FooImplementation1), typeof(FooImplementation2) }, ctx); Assert.True(catalog.Parts.Count() == 0); } [Fact] public void OfTypeOnePart_ShouldFindOnePart() { var ctx = new RegistrationBuilder(); ctx.ForType<FooImplementation1>().Export(); var catalog = new TypeCatalog(new[] { typeof(IFoo), typeof(FooImplementation1), typeof(FooImplementation2) }, ctx); Assert.True(catalog.Parts.Count() == 1); } [Fact] public void OfTypeTwoPart_ShouldFindTwoParts() { var ctx = new RegistrationBuilder(); ctx.ForType<FooImplementation1>().Export(); ctx.ForType<FooImplementation2>().Export(); var catalog = new TypeCatalog(new[] { typeof(IFoo), typeof(FooImplementation1), typeof(FooImplementation2) }, ctx); Assert.True(catalog.Parts.Count() == 2); } [Fact] public void OfTypeTwoPart_ConfigurationAfterConstruction_ShouldFindTwoParts() { var ctx = new RegistrationBuilder(); var catalog = new TypeCatalog(new[] { typeof(IFoo), typeof(FooImplementation1), typeof(FooImplementation2) }, ctx); ctx.ForType<FooImplementation1>().Export(); ctx.ForType<FooImplementation2>().Export(); Assert.True(catalog.Parts.Count() == 2); } [Fact] public void OfTypeTwoPart_ConfigurationAfterParts_ShouldFindZeroParts() { var ctx = new RegistrationBuilder(); var catalog = new TypeCatalog(new[] { typeof(IFoo), typeof(FooImplementation1), typeof(FooImplementation2) }, ctx); Assert.True(catalog.Parts.Count() == 0); ctx.ForType<FooImplementation1>().Export(); ctx.ForType<FooImplementation2>().Export(); Assert.True(catalog.Parts.Count() == 0); } [Fact] public void WhereNullArgument_ShouldThrowArgumentException() { Assert.Throws<ArgumentNullException>("typeFilter", () => { var ctx = new RegistrationBuilder(); ctx.ForTypesMatching(null); var catalog = new TypeCatalog(new[] { typeof(IFoo), typeof(FooImplementation1), typeof(FooImplementation2) }, ctx); Assert.True(catalog.Parts.Count() == 0); }); } [Fact] public void WhereIsClassAndImplementsIFooNoExport_ShouldFindZeroParts() { var ctx = new RegistrationBuilder(); // Implements<IFoo> ctx.ForTypesMatching((t) => { return t.IsClass && typeof(IFoo).IsAssignableFrom(t); }); var catalog = new TypeCatalog(new[] { typeof(IFoo), typeof(FooImplementation1), typeof(FooImplementation2) }, ctx); Assert.True(catalog.Parts.Count() == 0); } [Fact] public void WhereIsClassAndImplementsIFooWithExport_ShouldFindTwoParts() { var ctx = new RegistrationBuilder(); // Implements<IFoo> ctx.ForTypesMatching((t) => { return t.IsClass && typeof(IFoo).IsAssignableFrom(t); }).Export(); var catalog = new TypeCatalog(new[] { typeof(IFoo), typeof(FooImplementation1), typeof(FooImplementation2) }, ctx); Assert.True(catalog.Parts.Count() == 2); } [Fact] public void WhereIsTypeWithExport_ShouldFindTwoParts() { var ctx = new RegistrationBuilder(); // Implements<FooImplementation1> ctx.ForTypesMatching((t) => { return t.IsAssignableFrom(typeof(FooImplementation1)); }).Export(); // Implements<FooImplementation2> ctx.ForTypesMatching((t) => { return t.IsAssignableFrom(typeof(FooImplementation2)); }).Export(); var catalog = new TypeCatalog(new[] { typeof(IFoo), typeof(FooImplementation1), typeof(FooImplementation2) }, ctx); Assert.True(catalog.Parts.Count() == 2); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel.Composition.Hosting; using System.Linq; using Xunit; namespace System.ComponentModel.Composition.Registration.Tests { public interface IFoo { } public class FooImplementation1 : IFoo { } public class FooImplementation2 : IFoo { } public class RegistrationBuilderUnitTests { [Fact] public void UndecoratedContext_ShouldFindZeroParts() { var ctx = new RegistrationBuilder(); var catalog = new TypeCatalog(new[] { typeof(IFoo), typeof(FooImplementation1), typeof(FooImplementation2) }, ctx); Assert.True(catalog.Parts.Count() == 0); } [Fact] public void ImplementsIFooNoExport_ShouldFindZeroParts() { var ctx = new RegistrationBuilder(); ctx.ForTypesDerivedFrom<IFoo>(); var catalog = new TypeCatalog(new[] { typeof(IFoo), typeof(FooImplementation1), typeof(FooImplementation2) }, ctx); Assert.True(catalog.Parts.Count() == 0); } [Fact] public void ImplementsIFooWithExport_ShouldFindTwoParts() { var ctx = new RegistrationBuilder(); ctx.ForTypesDerivedFrom<IFoo>().Export(); var catalog = new TypeCatalog(new[] { typeof(IFoo), typeof(FooImplementation1), typeof(FooImplementation2) }, ctx); Assert.True(catalog.Parts.Count() == 2); } [Fact] public void OfTypeInterfaceNoExport_ShouldFindZeroParts() { var ctx = new RegistrationBuilder(); ctx.ForType<IFoo>(); var catalog = new TypeCatalog(new[] { typeof(IFoo), typeof(FooImplementation1), typeof(FooImplementation2) }, ctx); Assert.True(catalog.Parts.Count() == 0); } [Fact] public void OfTypeInterfaceWithExport_ShouldFindZeroParts() { var ctx = new RegistrationBuilder(); ctx.ForType<IFoo>().Export(); var catalog = new TypeCatalog(new[] { typeof(IFoo), typeof(FooImplementation1), typeof(FooImplementation2) }, ctx); Assert.True(catalog.Parts.Count() == 0); } [Fact] public void OfTypeOnePart_ShouldFindOnePart() { var ctx = new RegistrationBuilder(); ctx.ForType<FooImplementation1>().Export(); var catalog = new TypeCatalog(new[] { typeof(IFoo), typeof(FooImplementation1), typeof(FooImplementation2) }, ctx); Assert.True(catalog.Parts.Count() == 1); } [Fact] public void OfTypeTwoPart_ShouldFindTwoParts() { var ctx = new RegistrationBuilder(); ctx.ForType<FooImplementation1>().Export(); ctx.ForType<FooImplementation2>().Export(); var catalog = new TypeCatalog(new[] { typeof(IFoo), typeof(FooImplementation1), typeof(FooImplementation2) }, ctx); Assert.True(catalog.Parts.Count() == 2); } [Fact] public void OfTypeTwoPart_ConfigurationAfterConstruction_ShouldFindTwoParts() { var ctx = new RegistrationBuilder(); var catalog = new TypeCatalog(new[] { typeof(IFoo), typeof(FooImplementation1), typeof(FooImplementation2) }, ctx); ctx.ForType<FooImplementation1>().Export(); ctx.ForType<FooImplementation2>().Export(); Assert.True(catalog.Parts.Count() == 2); } [Fact] public void OfTypeTwoPart_ConfigurationAfterParts_ShouldFindZeroParts() { var ctx = new RegistrationBuilder(); var catalog = new TypeCatalog(new[] { typeof(IFoo), typeof(FooImplementation1), typeof(FooImplementation2) }, ctx); Assert.True(catalog.Parts.Count() == 0); ctx.ForType<FooImplementation1>().Export(); ctx.ForType<FooImplementation2>().Export(); Assert.True(catalog.Parts.Count() == 0); } [Fact] public void WhereNullArgument_ShouldThrowArgumentException() { Assert.Throws<ArgumentNullException>("typeFilter", () => { var ctx = new RegistrationBuilder(); ctx.ForTypesMatching(null); var catalog = new TypeCatalog(new[] { typeof(IFoo), typeof(FooImplementation1), typeof(FooImplementation2) }, ctx); Assert.True(catalog.Parts.Count() == 0); }); } [Fact] public void WhereIsClassAndImplementsIFooNoExport_ShouldFindZeroParts() { var ctx = new RegistrationBuilder(); // Implements<IFoo> ctx.ForTypesMatching((t) => { return t.IsClass && typeof(IFoo).IsAssignableFrom(t); }); var catalog = new TypeCatalog(new[] { typeof(IFoo), typeof(FooImplementation1), typeof(FooImplementation2) }, ctx); Assert.True(catalog.Parts.Count() == 0); } [Fact] public void WhereIsClassAndImplementsIFooWithExport_ShouldFindTwoParts() { var ctx = new RegistrationBuilder(); // Implements<IFoo> ctx.ForTypesMatching((t) => { return t.IsClass && typeof(IFoo).IsAssignableFrom(t); }).Export(); var catalog = new TypeCatalog(new[] { typeof(IFoo), typeof(FooImplementation1), typeof(FooImplementation2) }, ctx); Assert.True(catalog.Parts.Count() == 2); } [Fact] public void WhereIsTypeWithExport_ShouldFindTwoParts() { var ctx = new RegistrationBuilder(); // Implements<FooImplementation1> ctx.ForTypesMatching((t) => { return t.IsAssignableFrom(typeof(FooImplementation1)); }).Export(); // Implements<FooImplementation2> ctx.ForTypesMatching((t) => { return t.IsAssignableFrom(typeof(FooImplementation2)); }).Export(); var catalog = new TypeCatalog(new[] { typeof(IFoo), typeof(FooImplementation1), typeof(FooImplementation2) }, ctx); Assert.True(catalog.Parts.Count() == 2); } } }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./docs/workflow/building/coreclr/nativeaot.md
# Native AOT Developer Workflow The Native AOT toolchain can be currently built for Linux (x64/arm64), macOS (x64) and Windows (x64/arm64). ## High Level Overview Native AOT is a stripped down version of the CoreCLR runtime specialized for ahead of time compilation, with an accompanying ahead of time compiler. The main components of the toolchain are: * The AOT compiler (ILC/ILCompiler) built on a shared codebase with crossgen2 (src/coreclr/tools/aot). Where crossgen2 generates ReadyToRun modules that contain code and data structures for the CoreCLR runtime, ILC generates code and self-describing datastructures for a stripped down version of CoreCLR into object files. The object files use platform specific file formats (COFF with CodeView on Windows, ELF with DWARF on Linux, and Mach-O with DWARF on macOS). * The stripped down CoreCLR runtime (NativeAOT specific files in src/coreclr/nativeaot/Runtime, the rest included from the src/coreclr). The stripped down runtime is built into a static library that is linked with object file generated by the AOT compiler using a platform-specific linker (link.exe on Windows, ld on Linux/macOS) to form a standalone executable. * The bootstrapper library (src/coreclr/nativeaot/Bootstrap). This is a small native library that contains the actual native `main()` entrypoint and bootstraps the runtime and dispatches to managed code. Two flavors of the bootstrapper are built - one for executables, and another for dynamic libraries. * The core libraries (src/coreclr/nativeaot): System.Private.CoreLib (corelib), System.Private.Reflection.* (the implementation of reflection), System.Private.TypeLoader (ability to load new types that were not generated statically). * The dotnet integration (src/coreclr/nativeaot/BuildIntegration). This is a set of .targets/.props files that hook into `dotnet publish` to run the AOT compiler and execute the platform linker. The AOT compiler typically takes the app, core libraries, and framework libraries as input. It then compiles the whole program into a single object file. Then the object file is linked to form a runnable executable. The executable is standalone (doesn't require a runtime), modulo any managed DllImports. The executable looks like a native executable, in the sense that it can be debugged with native debuggers and have full-fidelity access to locals, and stepping information. The compiler also has a mode where each managed assembly can be compiled into a separate object file. The object files are later linked into a single executable using the platform linker. This mode is mostly used in testing (it's faster to compile this way because we don't need to recompiling the same code from e.g. CoreLib). It's not a shipping configuration and has many problems (requires exactly matching compilation settings, forfeits many optimizations, and has trouble around cross-module generic virtual method implementations). ## Building - [Install pre-requisites](../../README.md#build-requirements) - Run `build[.cmd|.sh] clr+libs -rc [Debug|Release] -lc Release` from the repo root. This will restore nuget packages required for building and build the parts of the repo required for general CoreCLR development. Alternatively, instead of specifying `clr+libs`, you can specify `clr.alljits+clr.tools+clr.nativeaotlibs+clr.nativeaotruntime+libs` which is more targeted and builds faster. - [NOT PORTED OVER YET] The build will place the toolchain packages at `artifacts\packages\[Debug|Release]\Shipping`. To publish your project using these packages: - [NOT PORTED OVER YET] Add the package directory to your `nuget.config` file. For example, replace `dotnet-experimental` line in `samples\HelloWorld\nuget.config` with `<add key="local" value="C:\runtimelab\artifacts\packages\Debug\Shipping" />` - [NOT PORTED OVER YET] Run `dotnet publish --packages pkg -r [win-x64|linux-x64|osx-64] -c [Debug|Release]` to publish your project. `--packages pkg` option restores the package into a local directory that is easy to cleanup once you are done. It avoids polluting the global nuget cache with your locally built dev package. - The component that writes out object files (objwriter.dll/libobjwriter.so/libobjwriter.dylib) is based on LLVM and doesn't build in the runtime repo. It gets published as a NuGet package out of the dotnet/llvm-project repo (branch objwriter/12.x). If you're working on ObjWriter or bringing up a new platform that doesn't have ObjWriter packages yet, as additional pre-requiresites you need to build objwriter out of that repo and replace the file in the output. ## Visual Studio Solutions The repository has a number of Visual Studio Solutions files (`*.sln`) that are useful for editing parts of the repository. Build the repo from command line first before building using the solution files. Remember to select the appropriate configuration that you built. By default, `build.cmd` builds Debug x64 and so `Debug` and `x64` must be selected in the solution build configuration drop downs. - `src\coreclr\nativeaot\nativeaot.sln`. This solution is for the runtime libraries. - `src\coreclr\tools\aot\ilc.sln`. This solution is for the compiler. Typical workflow for working on the compiler: - Open `ilc.sln` in Visual Studio - Set "ILCompiler" project in solution explorer as your startup project - Set Working directory in the project Debug options to your test project directory, e.g. `C:\runtimelab\samples\HelloWorld` - Set Application arguments in the project Debug options to the response file that was generated by regular native aot publishing of your test project, e.g. `@obj\Release\net6.0\win-x64\native\HelloWorld.ilc.rsp` - Build & run using **F5** ## Convenience Visual Studio "repro" project Typical native AOT runtime developer scenario workflow is to native AOT compile a short piece of C# and run it. The repo contains helper projects that make debugging the AOT compiler and the runtime easier. The workflow looks like this: - Build the repo using the Building instructions above - Open the ilc.sln solution described above. This solution contains the compiler, but also an unrelated project named "repro". This repro project is a small Hello World. You can place any piece of C# you would like to compile in it. Building the project will compile the source code into IL, but also generate a response file that is suitable to pass to the AOT compiler. - Make sure you set the solution configuration in VS to the configuration you just built (e.g. x64 Debug). - In the ILCompiler project properties, on the Debug tab, set the "Application arguments" to the generated response file. This will be a file such as "C:\runtime\artifacts\bin\repro\x64\Debug\compile-with-Release-libs.rsp". Prefix the path to the file with "@" to indicate this is a response file so that the "Application arguments" field looks like "@some\path\to\file.rsp". - Build & run ILCompiler using **F5**. This will compile the repro project into an `.obj` file. You can debug the compiler and set breakpoints in it at this point. - The last step is linking the object file into an executable so that we can launch the result of the AOT compilation. - Open the src\coreclr\tools\aot\ILCompiler\reproNative\reproNative.vcxproj project in Visual Studio. This project is configured to pick up the `.obj` file we just compiled and link it with the rest of the runtime. - Set the solution configuration to the tuple you've been using so far (e.g. x64 Debug) - Build & run using **F5**. This will run the platform linker to link the obj file with the runtime and launch it. At this point you can debug the runtime and the various System.Private libraries. ## Running tests If you haven't built the tests yet, run `src\tests\build.cmd nativeaot [Debug|Release] tree nativeaot` on Windows, or `src/tests/build.sh -nativeaot [Debug|Release] -tree:nativeaot` on Linux. This will build the smoke tests only - they usually suffice to ensure the runtime and compiler is in a workable shape. To build all Pri-0 tests, drop the `tree nativeaot` parameter. The `Debug`/`Release` parameter should match the build configuration you used to build the runtime. To run all the tests that got built, run `src\tests\run.cmd runnativeaottests [Debug|Release]` on Windows, or `src/tests/run.sh --runnativeaottests [Debug|Release]` on Linux. The `Debug`/`Release` flag should match the flag that was passed to `build.cmd` in the previous step. To run an individual test (after it was built), navigate to the `artifacts\tests\coreclr\[Windows|Linux|OSX[.x64.[Debug|Release]\$path_to_test` directory. `$path_to_test` matches the subtree of `src\tests`. You should see a `[.cmd|.sh]` file there. This file is a script that will compile and launch the individual test for you. Before invoking the script, set the following environment variables: * CORE_ROOT=$repo_root\artifacts\tests\coreclr\[Windows|Linux|OSX].x64.[Debug|Release]\Tests\Core_Root * CLRCustomTestLauncher=$repo_root\src\tests\Common\scripts\nativeaottest[.cmd|.sh] `$repo_root` is the root of your clone of the repo. Sometimes it's handy to be able to rebuild the managed test manually or run the compilation under a debugger. A response file that was used to invoke the ahead of time compiler can be found in `$repo_root\artifacts\tests\coreclr\obj\[Windows|Linux|OSX].x64.[Debug|Release]\Managed`. For more advanced scenarios, look for at [Building Test Subsets](../../testing/coreclr/windows-test-instructions.md#building-test-subsets) and [Generating Core_Root](../../testing/coreclr/windows-test-instructions.md#generating-core_root) ## Design Documentation - [ILC Compiler Architecture](../../../design/coreclr/botr/ilc-architecture.md) - [Managed Type System](../../../design/coreclr/botr/managed-type-system.md)
# Native AOT Developer Workflow The Native AOT toolchain can be currently built for Linux (x64/arm64), macOS (x64) and Windows (x64/arm64). ## High Level Overview Native AOT is a stripped down version of the CoreCLR runtime specialized for ahead of time compilation, with an accompanying ahead of time compiler. The main components of the toolchain are: * The AOT compiler (ILC/ILCompiler) built on a shared codebase with crossgen2 (src/coreclr/tools/aot). Where crossgen2 generates ReadyToRun modules that contain code and data structures for the CoreCLR runtime, ILC generates code and self-describing datastructures for a stripped down version of CoreCLR into object files. The object files use platform specific file formats (COFF with CodeView on Windows, ELF with DWARF on Linux, and Mach-O with DWARF on macOS). * The stripped down CoreCLR runtime (NativeAOT specific files in src/coreclr/nativeaot/Runtime, the rest included from the src/coreclr). The stripped down runtime is built into a static library that is linked with object file generated by the AOT compiler using a platform-specific linker (link.exe on Windows, ld on Linux/macOS) to form a standalone executable. * The bootstrapper library (src/coreclr/nativeaot/Bootstrap). This is a small native library that contains the actual native `main()` entrypoint and bootstraps the runtime and dispatches to managed code. Two flavors of the bootstrapper are built - one for executables, and another for dynamic libraries. * The core libraries (src/coreclr/nativeaot): System.Private.CoreLib (corelib), System.Private.Reflection.* (the implementation of reflection), System.Private.TypeLoader (ability to load new types that were not generated statically). * The dotnet integration (src/coreclr/nativeaot/BuildIntegration). This is a set of .targets/.props files that hook into `dotnet publish` to run the AOT compiler and execute the platform linker. The AOT compiler typically takes the app, core libraries, and framework libraries as input. It then compiles the whole program into a single object file. Then the object file is linked to form a runnable executable. The executable is standalone (doesn't require a runtime), modulo any managed DllImports. The executable looks like a native executable, in the sense that it can be debugged with native debuggers and have full-fidelity access to locals, and stepping information. The compiler also has a mode where each managed assembly can be compiled into a separate object file. The object files are later linked into a single executable using the platform linker. This mode is mostly used in testing (it's faster to compile this way because we don't need to recompiling the same code from e.g. CoreLib). It's not a shipping configuration and has many problems (requires exactly matching compilation settings, forfeits many optimizations, and has trouble around cross-module generic virtual method implementations). ## Building - [Install pre-requisites](../../README.md#build-requirements) - Run `build[.cmd|.sh] clr+libs -rc [Debug|Release] -lc Release` from the repo root. This will restore nuget packages required for building and build the parts of the repo required for general CoreCLR development. Alternatively, instead of specifying `clr+libs`, you can specify `clr.alljits+clr.tools+clr.nativeaotlibs+clr.nativeaotruntime+libs` which is more targeted and builds faster. - [NOT PORTED OVER YET] The build will place the toolchain packages at `artifacts\packages\[Debug|Release]\Shipping`. To publish your project using these packages: - [NOT PORTED OVER YET] Add the package directory to your `nuget.config` file. For example, replace `dotnet-experimental` line in `samples\HelloWorld\nuget.config` with `<add key="local" value="C:\runtimelab\artifacts\packages\Debug\Shipping" />` - [NOT PORTED OVER YET] Run `dotnet publish --packages pkg -r [win-x64|linux-x64|osx-64] -c [Debug|Release]` to publish your project. `--packages pkg` option restores the package into a local directory that is easy to cleanup once you are done. It avoids polluting the global nuget cache with your locally built dev package. - The component that writes out object files (objwriter.dll/libobjwriter.so/libobjwriter.dylib) is based on LLVM and doesn't build in the runtime repo. It gets published as a NuGet package out of the dotnet/llvm-project repo (branch objwriter/12.x). If you're working on ObjWriter or bringing up a new platform that doesn't have ObjWriter packages yet, as additional pre-requiresites you need to build objwriter out of that repo and replace the file in the output. ## Visual Studio Solutions The repository has a number of Visual Studio Solutions files (`*.sln`) that are useful for editing parts of the repository. Build the repo from command line first before building using the solution files. Remember to select the appropriate configuration that you built. By default, `build.cmd` builds Debug x64 and so `Debug` and `x64` must be selected in the solution build configuration drop downs. - `src\coreclr\nativeaot\nativeaot.sln`. This solution is for the runtime libraries. - `src\coreclr\tools\aot\ilc.sln`. This solution is for the compiler. Typical workflow for working on the compiler: - Open `ilc.sln` in Visual Studio - Set "ILCompiler" project in solution explorer as your startup project - Set Working directory in the project Debug options to your test project directory, e.g. `C:\runtimelab\samples\HelloWorld` - Set Application arguments in the project Debug options to the response file that was generated by regular native aot publishing of your test project, e.g. `@obj\Release\net6.0\win-x64\native\HelloWorld.ilc.rsp` - Build & run using **F5** ## Convenience Visual Studio "repro" project Typical native AOT runtime developer scenario workflow is to native AOT compile a short piece of C# and run it. The repo contains helper projects that make debugging the AOT compiler and the runtime easier. The workflow looks like this: - Build the repo using the Building instructions above - Open the ilc.sln solution described above. This solution contains the compiler, but also an unrelated project named "repro". This repro project is a small Hello World. You can place any piece of C# you would like to compile in it. Building the project will compile the source code into IL, but also generate a response file that is suitable to pass to the AOT compiler. - Make sure you set the solution configuration in VS to the configuration you just built (e.g. x64 Debug). - In the ILCompiler project properties, on the Debug tab, set the "Application arguments" to the generated response file. This will be a file such as "C:\runtime\artifacts\bin\repro\x64\Debug\compile-with-Release-libs.rsp". Prefix the path to the file with "@" to indicate this is a response file so that the "Application arguments" field looks like "@some\path\to\file.rsp". - Build & run ILCompiler using **F5**. This will compile the repro project into an `.obj` file. You can debug the compiler and set breakpoints in it at this point. - The last step is linking the object file into an executable so that we can launch the result of the AOT compilation. - Open the src\coreclr\tools\aot\ILCompiler\reproNative\reproNative.vcxproj project in Visual Studio. This project is configured to pick up the `.obj` file we just compiled and link it with the rest of the runtime. - Set the solution configuration to the tuple you've been using so far (e.g. x64 Debug) - Build & run using **F5**. This will run the platform linker to link the obj file with the runtime and launch it. At this point you can debug the runtime and the various System.Private libraries. ## Running tests If you haven't built the tests yet, run `src\tests\build.cmd nativeaot [Debug|Release] tree nativeaot` on Windows, or `src/tests/build.sh -nativeaot [Debug|Release] -tree:nativeaot` on Linux. This will build the smoke tests only - they usually suffice to ensure the runtime and compiler is in a workable shape. To build all Pri-0 tests, drop the `tree nativeaot` parameter. The `Debug`/`Release` parameter should match the build configuration you used to build the runtime. To run all the tests that got built, run `src\tests\run.cmd runnativeaottests [Debug|Release]` on Windows, or `src/tests/run.sh --runnativeaottests [Debug|Release]` on Linux. The `Debug`/`Release` flag should match the flag that was passed to `build.cmd` in the previous step. To run an individual test (after it was built), navigate to the `artifacts\tests\coreclr\[Windows|Linux|OSX[.x64.[Debug|Release]\$path_to_test` directory. `$path_to_test` matches the subtree of `src\tests`. You should see a `[.cmd|.sh]` file there. This file is a script that will compile and launch the individual test for you. Before invoking the script, set the following environment variables: * CORE_ROOT=$repo_root\artifacts\tests\coreclr\[Windows|Linux|OSX].x64.[Debug|Release]\Tests\Core_Root * CLRCustomTestLauncher=$repo_root\src\tests\Common\scripts\nativeaottest[.cmd|.sh] `$repo_root` is the root of your clone of the repo. Sometimes it's handy to be able to rebuild the managed test manually or run the compilation under a debugger. A response file that was used to invoke the ahead of time compiler can be found in `$repo_root\artifacts\tests\coreclr\obj\[Windows|Linux|OSX].x64.[Debug|Release]\Managed`. For more advanced scenarios, look for at [Building Test Subsets](../../testing/coreclr/windows-test-instructions.md#building-test-subsets) and [Generating Core_Root](../../testing/coreclr/windows-test-instructions.md#generating-core_root) ## Design Documentation - [ILC Compiler Architecture](../../../design/coreclr/botr/ilc-architecture.md) - [Managed Type System](../../../design/coreclr/botr/managed-type-system.md)
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/libraries/System.Net.Sockets/tests/FunctionalTests/TcpListenerTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Net.Sockets.Tests { public class TcpListenerTest { [Fact] public void Ctor_InvalidArguments_Throws() { AssertExtensions.Throws<ArgumentNullException>("localEP", () => new TcpListener(null)); AssertExtensions.Throws<ArgumentNullException>("localaddr", () => new TcpListener(null, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("port", () => new TcpListener(IPAddress.Loopback, -1)); #pragma warning disable 0618 // ctor is obsolete AssertExtensions.Throws<ArgumentOutOfRangeException>("port", () => new TcpListener(66000)); #pragma warning restore 0618 AssertExtensions.Throws<ArgumentOutOfRangeException>("port", () => TcpListener.Create(66000)); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] public void Active_TrueWhileRunning(int ctor) { var listener = ctor == 0 ? new DerivedTcpListener(new IPEndPoint(IPAddress.Loopback, 0)) : ctor == 1 ? new DerivedTcpListener(IPAddress.Loopback, 0) : new DerivedTcpListener(0); Assert.False(listener.Active); listener.Start(); Assert.True(listener.Active); Assert.Throws<InvalidOperationException>(() => listener.AllowNatTraversal(false)); Assert.Throws<InvalidOperationException>(() => listener.ExclusiveAddressUse = true); Assert.Throws<InvalidOperationException>(() => listener.ExclusiveAddressUse = false); bool ignored = listener.ExclusiveAddressUse; // we can get it while active, just not set it listener.Stop(); Assert.False(listener.Active); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void AllowNatTraversal_NotStarted_SetSuccessfully() { var listener = new TcpListener(IPAddress.Loopback, 0); listener.AllowNatTraversal(true); listener.Start(); listener.Stop(); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void AllowNatTraversal_Started_ThrowsException() { var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); Assert.Throws<InvalidOperationException>(() => listener.AllowNatTraversal(true)); listener.Stop(); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void AllowNatTraversal_StartedAndStopped_SetSuccessfully() { var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); listener.Stop(); listener.AllowNatTraversal(true); } [Fact] public void Start_InvalidArgs_Throws() { var listener = new DerivedTcpListener(IPAddress.Loopback, 0); Assert.Throws<ArgumentOutOfRangeException>(() => listener.Start(-1)); Assert.False(listener.Active); listener.Start(1); listener.Start(1); // ok to call twice listener.Stop(); } [Fact] public async Task Pending_TrueWhenWaitingRequest() { var listener = new TcpListener(IPAddress.Loopback, 0); Assert.Throws<InvalidOperationException>(() => listener.Pending()); listener.Start(); Assert.False(listener.Pending()); using (TcpClient client = new TcpClient(new IPEndPoint(IPAddress.Loopback, 0))) { Task connectTask = client.ConnectAsync(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port); Assert.True(SpinWait.SpinUntil(() => listener.Pending(), 30000), "Expected Pending to be true within timeout"); listener.AcceptSocket().Dispose(); await connectTask; } listener.Stop(); Assert.Throws<InvalidOperationException>(() => listener.Pending()); } [Fact] public void Accept_Invalid_Throws() { var listener = new TcpListener(IPAddress.Loopback, 0); Assert.Throws<InvalidOperationException>(() => listener.AcceptSocket()); Assert.Throws<InvalidOperationException>(() => listener.AcceptTcpClient()); Assert.Throws<InvalidOperationException>(() => listener.BeginAcceptSocket(null, null)); Assert.Throws<InvalidOperationException>(() => listener.BeginAcceptTcpClient(null, null)); Assert.Throws<InvalidOperationException>(() => { listener.AcceptSocketAsync(); }); Assert.Throws<InvalidOperationException>(() => { listener.AcceptTcpClientAsync(); }); Assert.Throws<ArgumentNullException>(() => listener.EndAcceptSocket(null)); Assert.Throws<ArgumentNullException>(() => listener.EndAcceptTcpClient(null)); AssertExtensions.Throws<ArgumentException>("asyncResult", () => listener.EndAcceptSocket(Task.CompletedTask)); AssertExtensions.Throws<ArgumentException>("asyncResult", () => listener.EndAcceptTcpClient(Task.CompletedTask)); } [Theory] [InlineData(0)] // Sync [InlineData(1)] // Async [InlineData(2)] // Async with Cancellation [InlineData(3)] // APM [ActiveIssue("https://github.com/dotnet/runtime/issues/51392", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public async Task Accept_AcceptsPendingSocketOrClient(int mode) { var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); using (var client = new TcpClient()) { Task connectTask = client.ConnectAsync(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port); using (Socket s = mode switch { 0 => listener.AcceptSocket(), 1 => await listener.AcceptSocketAsync(), 2 => await listener.AcceptSocketAsync(CancellationToken.None), _ => await Task.Factory.FromAsync(listener.BeginAcceptSocket, listener.EndAcceptSocket, null), }) { Assert.False(listener.Pending()); } await connectTask; } using (var client = new TcpClient()) { Task connectTask = client.ConnectAsync(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port); using (TcpClient c = mode switch { 0 => listener.AcceptTcpClient(), 1 => await listener.AcceptTcpClientAsync(), 2 => await listener.AcceptTcpClientAsync(CancellationToken.None), _ => await Task.Factory.FromAsync(listener.BeginAcceptTcpClient, listener.EndAcceptTcpClient, null), }) { Assert.False(listener.Pending()); } await connectTask; } listener.Stop(); } [Fact] // This verify that basic constructs do work when IPv6 is NOT available. public void IPv6_Only_Works() { if (Socket.OSSupportsIPv6 || !Socket.OSSupportsIPv4) { // TBD we should figure out better way how to execute this in IPv4 only environment. return; } // This should not throw e.g. default to IPv6. TcpListener l = TcpListener.Create(0); l.Stop(); Socket s = new Socket(SocketType.Stream, ProtocolType.Tcp); s.Close(); } [Fact] public async Task Accept_StartAfterStop_AcceptsSuccessfully() { var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); await VerifyAccept(listener); listener.Stop(); Assert.NotNull(listener.Server); listener.Start(); Assert.NotNull(listener.Server); await VerifyAccept(listener); listener.Stop(); async Task VerifyAccept(TcpListener listener) { using var client = new TcpClient(); Task connectTask = client.ConnectAsync(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port); using Socket s = await listener.AcceptSocketAsync(); Assert.False(listener.Pending()); await connectTask; } } [Fact] public void ExclusiveAddressUse_ListenerNotStarted_SetAndReadSuccessfully() { var listener = new TcpListener(IPAddress.Loopback, 0); listener.ExclusiveAddressUse = true; Assert.True(listener.ExclusiveAddressUse); listener.ExclusiveAddressUse = false; Assert.False(listener.ExclusiveAddressUse); } [Fact] public void ExclusiveAddressUse_SetStartListenerThenRead_ReadSuccessfully() { var listener = new TcpListener(IPAddress.Loopback, 0); listener.ExclusiveAddressUse = true; listener.Start(); Assert.True(listener.ExclusiveAddressUse); listener.Stop(); Assert.True(listener.ExclusiveAddressUse); } [Fact] public void ExclusiveAddressUse_SetStartAndStopListenerThenRead_ReadSuccessfully() { var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); listener.Stop(); listener.ExclusiveAddressUse = true; Assert.True(listener.ExclusiveAddressUse); listener.Start(); Assert.True(listener.ExclusiveAddressUse); listener.Stop(); Assert.True(listener.ExclusiveAddressUse); } [Fact] public void EndAcceptSocket_WhenStopped_ThrowsObjectDisposedException() { var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); IAsyncResult iar = listener.BeginAcceptSocket(callback: null, state: null); // Give some time for the underlying OS operation to start: Thread.Sleep(50); listener.Stop(); Assert.Throws<ObjectDisposedException>(() => listener.EndAcceptSocket(iar)); } [Fact] public void EndAcceptTcpClient_WhenStopped_ThrowsObjectDisposedException() { var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); IAsyncResult iar = listener.BeginAcceptTcpClient(callback: null, state: null); // Give some time for the underlying OS operation to start: Thread.Sleep(50); listener.Stop(); Assert.Throws<ObjectDisposedException>(() => listener.EndAcceptTcpClient(iar)); } private sealed class DerivedTcpListener : TcpListener { #pragma warning disable 0618 public DerivedTcpListener(int port) : base(port) { } #pragma warning restore 0618 public DerivedTcpListener(IPEndPoint endpoint) : base(endpoint) { } public DerivedTcpListener(IPAddress address, int port) : base(address, port) { } public new bool Active => base.Active; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Net.Sockets.Tests { public class TcpListenerTest { [Fact] public void Ctor_InvalidArguments_Throws() { AssertExtensions.Throws<ArgumentNullException>("localEP", () => new TcpListener(null)); AssertExtensions.Throws<ArgumentNullException>("localaddr", () => new TcpListener(null, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("port", () => new TcpListener(IPAddress.Loopback, -1)); #pragma warning disable 0618 // ctor is obsolete AssertExtensions.Throws<ArgumentOutOfRangeException>("port", () => new TcpListener(66000)); #pragma warning restore 0618 AssertExtensions.Throws<ArgumentOutOfRangeException>("port", () => TcpListener.Create(66000)); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] public void Active_TrueWhileRunning(int ctor) { var listener = ctor == 0 ? new DerivedTcpListener(new IPEndPoint(IPAddress.Loopback, 0)) : ctor == 1 ? new DerivedTcpListener(IPAddress.Loopback, 0) : new DerivedTcpListener(0); Assert.False(listener.Active); listener.Start(); Assert.True(listener.Active); Assert.Throws<InvalidOperationException>(() => listener.AllowNatTraversal(false)); Assert.Throws<InvalidOperationException>(() => listener.ExclusiveAddressUse = true); Assert.Throws<InvalidOperationException>(() => listener.ExclusiveAddressUse = false); bool ignored = listener.ExclusiveAddressUse; // we can get it while active, just not set it listener.Stop(); Assert.False(listener.Active); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void AllowNatTraversal_NotStarted_SetSuccessfully() { var listener = new TcpListener(IPAddress.Loopback, 0); listener.AllowNatTraversal(true); listener.Start(); listener.Stop(); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void AllowNatTraversal_Started_ThrowsException() { var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); Assert.Throws<InvalidOperationException>(() => listener.AllowNatTraversal(true)); listener.Stop(); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void AllowNatTraversal_StartedAndStopped_SetSuccessfully() { var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); listener.Stop(); listener.AllowNatTraversal(true); } [Fact] public void Start_InvalidArgs_Throws() { var listener = new DerivedTcpListener(IPAddress.Loopback, 0); Assert.Throws<ArgumentOutOfRangeException>(() => listener.Start(-1)); Assert.False(listener.Active); listener.Start(1); listener.Start(1); // ok to call twice listener.Stop(); } [Fact] public async Task Pending_TrueWhenWaitingRequest() { var listener = new TcpListener(IPAddress.Loopback, 0); Assert.Throws<InvalidOperationException>(() => listener.Pending()); listener.Start(); Assert.False(listener.Pending()); using (TcpClient client = new TcpClient(new IPEndPoint(IPAddress.Loopback, 0))) { Task connectTask = client.ConnectAsync(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port); Assert.True(SpinWait.SpinUntil(() => listener.Pending(), 30000), "Expected Pending to be true within timeout"); listener.AcceptSocket().Dispose(); await connectTask; } listener.Stop(); Assert.Throws<InvalidOperationException>(() => listener.Pending()); } [Fact] public void Accept_Invalid_Throws() { var listener = new TcpListener(IPAddress.Loopback, 0); Assert.Throws<InvalidOperationException>(() => listener.AcceptSocket()); Assert.Throws<InvalidOperationException>(() => listener.AcceptTcpClient()); Assert.Throws<InvalidOperationException>(() => listener.BeginAcceptSocket(null, null)); Assert.Throws<InvalidOperationException>(() => listener.BeginAcceptTcpClient(null, null)); Assert.Throws<InvalidOperationException>(() => { listener.AcceptSocketAsync(); }); Assert.Throws<InvalidOperationException>(() => { listener.AcceptTcpClientAsync(); }); Assert.Throws<ArgumentNullException>(() => listener.EndAcceptSocket(null)); Assert.Throws<ArgumentNullException>(() => listener.EndAcceptTcpClient(null)); AssertExtensions.Throws<ArgumentException>("asyncResult", () => listener.EndAcceptSocket(Task.CompletedTask)); AssertExtensions.Throws<ArgumentException>("asyncResult", () => listener.EndAcceptTcpClient(Task.CompletedTask)); } [Theory] [InlineData(0)] // Sync [InlineData(1)] // Async [InlineData(2)] // Async with Cancellation [InlineData(3)] // APM [ActiveIssue("https://github.com/dotnet/runtime/issues/51392", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public async Task Accept_AcceptsPendingSocketOrClient(int mode) { var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); using (var client = new TcpClient()) { Task connectTask = client.ConnectAsync(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port); using (Socket s = mode switch { 0 => listener.AcceptSocket(), 1 => await listener.AcceptSocketAsync(), 2 => await listener.AcceptSocketAsync(CancellationToken.None), _ => await Task.Factory.FromAsync(listener.BeginAcceptSocket, listener.EndAcceptSocket, null), }) { Assert.False(listener.Pending()); } await connectTask; } using (var client = new TcpClient()) { Task connectTask = client.ConnectAsync(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port); using (TcpClient c = mode switch { 0 => listener.AcceptTcpClient(), 1 => await listener.AcceptTcpClientAsync(), 2 => await listener.AcceptTcpClientAsync(CancellationToken.None), _ => await Task.Factory.FromAsync(listener.BeginAcceptTcpClient, listener.EndAcceptTcpClient, null), }) { Assert.False(listener.Pending()); } await connectTask; } listener.Stop(); } [Fact] // This verify that basic constructs do work when IPv6 is NOT available. public void IPv6_Only_Works() { if (Socket.OSSupportsIPv6 || !Socket.OSSupportsIPv4) { // TBD we should figure out better way how to execute this in IPv4 only environment. return; } // This should not throw e.g. default to IPv6. TcpListener l = TcpListener.Create(0); l.Stop(); Socket s = new Socket(SocketType.Stream, ProtocolType.Tcp); s.Close(); } [Fact] public async Task Accept_StartAfterStop_AcceptsSuccessfully() { var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); await VerifyAccept(listener); listener.Stop(); Assert.NotNull(listener.Server); listener.Start(); Assert.NotNull(listener.Server); await VerifyAccept(listener); listener.Stop(); async Task VerifyAccept(TcpListener listener) { using var client = new TcpClient(); Task connectTask = client.ConnectAsync(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port); using Socket s = await listener.AcceptSocketAsync(); Assert.False(listener.Pending()); await connectTask; } } [Fact] public void ExclusiveAddressUse_ListenerNotStarted_SetAndReadSuccessfully() { var listener = new TcpListener(IPAddress.Loopback, 0); listener.ExclusiveAddressUse = true; Assert.True(listener.ExclusiveAddressUse); listener.ExclusiveAddressUse = false; Assert.False(listener.ExclusiveAddressUse); } [Fact] public void ExclusiveAddressUse_SetStartListenerThenRead_ReadSuccessfully() { var listener = new TcpListener(IPAddress.Loopback, 0); listener.ExclusiveAddressUse = true; listener.Start(); Assert.True(listener.ExclusiveAddressUse); listener.Stop(); Assert.True(listener.ExclusiveAddressUse); } [Fact] public void ExclusiveAddressUse_SetStartAndStopListenerThenRead_ReadSuccessfully() { var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); listener.Stop(); listener.ExclusiveAddressUse = true; Assert.True(listener.ExclusiveAddressUse); listener.Start(); Assert.True(listener.ExclusiveAddressUse); listener.Stop(); Assert.True(listener.ExclusiveAddressUse); } [Fact] public void EndAcceptSocket_WhenStopped_ThrowsObjectDisposedException() { var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); IAsyncResult iar = listener.BeginAcceptSocket(callback: null, state: null); // Give some time for the underlying OS operation to start: Thread.Sleep(50); listener.Stop(); Assert.Throws<ObjectDisposedException>(() => listener.EndAcceptSocket(iar)); } [Fact] public void EndAcceptTcpClient_WhenStopped_ThrowsObjectDisposedException() { var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); IAsyncResult iar = listener.BeginAcceptTcpClient(callback: null, state: null); // Give some time for the underlying OS operation to start: Thread.Sleep(50); listener.Stop(); Assert.Throws<ObjectDisposedException>(() => listener.EndAcceptTcpClient(iar)); } private sealed class DerivedTcpListener : TcpListener { #pragma warning disable 0618 public DerivedTcpListener(int port) : base(port) { } #pragma warning restore 0618 public DerivedTcpListener(IPEndPoint endpoint) : base(endpoint) { } public DerivedTcpListener(IPAddress address, int port) : base(address, port) { } public new bool Active => base.Active; } } }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/tests/JIT/HardwareIntrinsics/X86/Avx2/Permute2x128.Avx2.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { static Program() { TestList = new Dictionary<string, Action>() { ["Permute2x128.Int32.2"] = Permute2x128Int322, ["Permute2x128.UInt32.2"] = Permute2x128UInt322, ["Permute2x128.Int64.2"] = Permute2x128Int642, ["Permute2x128.UInt64.2"] = Permute2x128UInt642, }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { static Program() { TestList = new Dictionary<string, Action>() { ["Permute2x128.Int32.2"] = Permute2x128Int322, ["Permute2x128.UInt32.2"] = Permute2x128UInt322, ["Permute2x128.Int64.2"] = Permute2x128Int642, ["Permute2x128.UInt64.2"] = Permute2x128UInt642, }; } } }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/tests/JIT/Methodical/Boxing/boxunbox/local_il_r.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="local.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="local.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/libraries/System.Globalization/tests/CultureInfo/CultureInfoAll.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using Microsoft.DotNet.RemoteExecutor; using System.Text; using System.Diagnostics; using Xunit; namespace System.Globalization.Tests { public class CultureInfoAll { [PlatformSpecific(TestPlatforms.Windows)] // P/Invoke to Win32 function [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNlsGlobalization))] public void TestAllCultures_Nls() { Assert.True(EnumSystemLocalesEx(EnumLocales, LOCALE_WINDOWS, IntPtr.Zero, IntPtr.Zero), "EnumSystemLocalesEx has failed"); Assert.All(cultures, Validate); } private void Validate(CultureInfo ci) { Assert.Equal(ci.EnglishName, GetLocaleInfo(ci, LOCALE_SENGLISHDISPLAYNAME)); // si-LK has some special case when running on Win7 so we just ignore this one if (!ci.Name.Equals("si-LK", StringComparison.OrdinalIgnoreCase)) { Assert.Equal(ci.Name.Length == 0 ? "Invariant Language (Invariant Country)" : GetLocaleInfo(ci, LOCALE_SNATIVEDISPLAYNAME), ci.NativeName); } // zh-Hans and zh-Hant has different behavior on different platform Assert.Contains(GetLocaleInfo(ci, LOCALE_SPARENT), new[] { "zh-Hans", "zh-Hant", ci.Parent.Name }, StringComparer.OrdinalIgnoreCase); Assert.Equal(ci.TwoLetterISOLanguageName, GetLocaleInfo(ci, LOCALE_SISO639LANGNAME)); ValidateDTFI(ci); ValidateNFI(ci); ValidateRegionInfo(ci); } private void ValidateDTFI(CultureInfo ci) { DateTimeFormatInfo dtfi = ci.DateTimeFormat; Calendar cal = dtfi.Calendar; int calId = GetCalendarId(cal); Assert.Equal(GetDayNames(ci, calId, CAL_SABBREVDAYNAME1), dtfi.AbbreviatedDayNames); Assert.Equal(GetDayNames(ci, calId, CAL_SDAYNAME1), dtfi.DayNames); Assert.Equal(GetMonthNames(ci, calId, CAL_SMONTHNAME1), dtfi.MonthNames); Assert.Equal(GetMonthNames(ci, calId, CAL_SABBREVMONTHNAME1), dtfi.AbbreviatedMonthNames); Assert.Equal(GetMonthNames(ci, calId, CAL_SMONTHNAME1 | LOCALE_RETURN_GENITIVE_NAMES), dtfi.MonthGenitiveNames); Assert.Equal(GetMonthNames(ci, calId, CAL_SABBREVMONTHNAME1 | LOCALE_RETURN_GENITIVE_NAMES), dtfi.AbbreviatedMonthGenitiveNames); Assert.Equal(GetDayNames(ci, calId, CAL_SSHORTESTDAYNAME1), dtfi.ShortestDayNames); Assert.Equal(GetLocaleInfo(ci, LOCALE_S1159), dtfi.AMDesignator, StringComparer.OrdinalIgnoreCase); Assert.Equal(GetLocaleInfo(ci, LOCALE_S2359), dtfi.PMDesignator, StringComparer.OrdinalIgnoreCase); Assert.Equal(calId, GetDefaultcalendar(ci)); Assert.Equal((int)dtfi.FirstDayOfWeek, ConvertFirstDayOfWeekMonToSun(GetLocaleInfoAsInt(ci, LOCALE_IFIRSTDAYOFWEEK))); Assert.Equal((int)dtfi.CalendarWeekRule, GetLocaleInfoAsInt(ci, LOCALE_IFIRSTWEEKOFYEAR)); Assert.Equal(dtfi.MonthDayPattern, GetCalendarInfo(ci, calId, CAL_SMONTHDAY, true)); Assert.Equal("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", dtfi.RFC1123Pattern); Assert.Equal("yyyy'-'MM'-'dd'T'HH':'mm':'ss", dtfi.SortableDateTimePattern); Assert.Equal("yyyy'-'MM'-'dd HH':'mm':'ss'Z'", dtfi.UniversalSortableDateTimePattern); string longDatePattern1 = GetCalendarInfo(ci, calId, CAL_SLONGDATE)[0]; string longDatePattern2 = ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SLONGDATE)); string longTimePattern1 = GetTimeFormats(ci, 0)[0]; string longTimePattern2 = ReescapeWin32String(GetLocaleInfo(ci, LOCALE_STIMEFORMAT)); string fullDateTimePattern = longDatePattern1 + " " + longTimePattern1; string fullDateTimePattern1 = longDatePattern2 + " " + longTimePattern2; Assert.Contains(dtfi.FullDateTimePattern, new[] { fullDateTimePattern, fullDateTimePattern1 }); Assert.Contains(dtfi.LongDatePattern, new[] { longDatePattern1, longDatePattern2 }); Assert.Contains(dtfi.LongTimePattern, new[] { longTimePattern1, longTimePattern2 }); Assert.Contains(dtfi.ShortTimePattern, new[] { GetTimeFormats(ci, TIME_NOSECONDS)[0], ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SSHORTTIME)) }); Assert.Contains(dtfi.ShortDatePattern, new[] { GetCalendarInfo(ci, calId, CAL_SSHORTDATE)[0], ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SSHORTDATE)) }); Assert.Contains(dtfi.YearMonthPattern, new[] { GetCalendarInfo(ci, calId, CAL_SYEARMONTH)[0], ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SYEARMONTH)) }); int eraNameIndex = 1; Assert.All(GetCalendarInfo(ci, calId, CAL_SERASTRING), eraName => Assert.Equal(dtfi.GetEraName(eraNameIndex++), eraName, StringComparer.OrdinalIgnoreCase)); eraNameIndex = 1; Assert.All(GetCalendarInfo(ci, calId, CAL_SABBREVERASTRING), eraName => Assert.Equal(dtfi.GetAbbreviatedEraName(eraNameIndex++), eraName, StringComparer.OrdinalIgnoreCase)); } private void ValidateNFI(CultureInfo ci) { NumberFormatInfo nfi = ci.NumberFormat; Assert.Equal(string.IsNullOrEmpty(GetLocaleInfo(ci, LOCALE_SPOSITIVESIGN)) ? "+" : GetLocaleInfo(ci, LOCALE_SPOSITIVESIGN), nfi.PositiveSign); Assert.Equal(GetLocaleInfo(ci, LOCALE_SNEGATIVESIGN), nfi.NegativeSign); Assert.Equal(GetLocaleInfo(ci, LOCALE_SDECIMAL), nfi.NumberDecimalSeparator); Assert.Equal(GetLocaleInfo(ci, LOCALE_SDECIMAL), nfi.PercentDecimalSeparator); Assert.Equal(GetLocaleInfo(ci, LOCALE_STHOUSAND), nfi.NumberGroupSeparator); Assert.Equal(GetLocaleInfo(ci, LOCALE_STHOUSAND), nfi.PercentGroupSeparator); Assert.Equal(GetLocaleInfo(ci, LOCALE_SMONTHOUSANDSEP), nfi.CurrencyGroupSeparator); Assert.Equal(GetLocaleInfo(ci, LOCALE_SMONDECIMALSEP), nfi.CurrencyDecimalSeparator); Assert.Equal(GetLocaleInfo(ci, LOCALE_SCURRENCY), nfi.CurrencySymbol); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IDIGITS), nfi.NumberDecimalDigits); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IDIGITS), nfi.PercentDecimalDigits); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_ICURRDIGITS), nfi.CurrencyDecimalDigits); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_ICURRENCY), nfi.CurrencyPositivePattern); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_INEGCURR), nfi.CurrencyNegativePattern); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_INEGNUMBER), nfi.NumberNegativePattern); Assert.Equal(ConvertWin32GroupString(GetLocaleInfo(ci, LOCALE_SMONGROUPING)), nfi.CurrencyGroupSizes); Assert.Equal(GetLocaleInfo(ci, LOCALE_SNAN), nfi.NaNSymbol); Assert.Equal(GetLocaleInfo(ci, LOCALE_SNEGINFINITY), nfi.NegativeInfinitySymbol); Assert.Equal(ConvertWin32GroupString(GetLocaleInfo(ci, LOCALE_SGROUPING)), nfi.NumberGroupSizes); Assert.Equal(ConvertWin32GroupString(GetLocaleInfo(ci, LOCALE_SGROUPING)), nfi.PercentGroupSizes); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_INEGATIVEPERCENT), nfi.PercentNegativePattern); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IPOSITIVEPERCENT), nfi.PercentPositivePattern); Assert.Equal(GetLocaleInfo(ci, LOCALE_SPERCENT), nfi.PercentSymbol); Assert.Equal(GetLocaleInfo(ci, LOCALE_SPERMILLE), nfi.PerMilleSymbol); Assert.Equal(GetLocaleInfo(ci, LOCALE_SPOSINFINITY), nfi.PositiveInfinitySymbol); } private void ValidateRegionInfo(CultureInfo ci) { if (ci.Name.Length == 0) // no region for invariant return; RegionInfo ri = new RegionInfo(ci.Name); Assert.Equal(GetLocaleInfo(ci, LOCALE_SCURRENCY), ri.CurrencySymbol); Assert.Equal(GetLocaleInfo(ci, LOCALE_SENGLISHCOUNTRYNAME), ri.EnglishName); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IMEASURE) == 0, ri.IsMetric); Assert.Equal(GetLocaleInfo(ci, LOCALE_SINTLSYMBOL), ri.ISOCurrencySymbol); Assert.True(ci.Name.Equals(ri.Name, StringComparison.OrdinalIgnoreCase) || // Desktop usese culture name as region name ri.Name.Equals(GetLocaleInfo(ci, LOCALE_SISO3166CTRYNAME), StringComparison.OrdinalIgnoreCase)); // netcore uses 2 letter ISO for region name Assert.Equal(GetLocaleInfo(ci, LOCALE_SISO3166CTRYNAME), ri.TwoLetterISORegionName, StringComparer.OrdinalIgnoreCase); Assert.Equal(GetLocaleInfo(ci, LOCALE_SNATIVECOUNTRYNAME), ri.NativeName, StringComparer.OrdinalIgnoreCase); } private int[] ConvertWin32GroupString(string win32Str) { // None of these cases make any sense if (win32Str == null || win32Str.Length == 0) { return (new int[] { 3 }); } if (win32Str[0] == '0') { return (new int[] { 0 }); } // Since its in n;n;n;n;n format, we can always get the length quickly int[] values; if (win32Str[win32Str.Length - 1] == '0') { // Trailing 0 gets dropped. 1;0 -> 1 values = new int[(win32Str.Length / 2)]; } else { // Need extra space for trailing zero 1 -> 1;0 values = new int[(win32Str.Length / 2) + 2]; values[values.Length - 1] = 0; } int i; int j; for (i = 0, j = 0; i < win32Str.Length && j < values.Length; i += 2, j++) { // Note that this # shouldn't ever be zero, 'cause 0 is only at end // But we'll test because its registry that could be anything if (win32Str[i] < '1' || win32Str[i] > '9') return new int[] { 3 }; values[j] = (int)(win32Str[i] - '0'); } return (values); } private List<string> _timePatterns; private bool EnumTimeFormats(string lpTimeFormatString, IntPtr lParam) { _timePatterns.Add(ReescapeWin32String(lpTimeFormatString)); return true; } private string[] GetTimeFormats(CultureInfo ci, uint flags) { _timePatterns = new List<string>(); Assert.True(EnumTimeFormatsEx(EnumTimeFormats, ci.Name, flags, IntPtr.Zero), string.Format("EnumTimeFormatsEx failed with culture {0} and flags {1}", ci, flags)); return _timePatterns.ToArray(); } internal string ReescapeWin32String(string str) { // If we don't have data, then don't try anything if (str == null) return null; StringBuilder result = null; bool inQuote = false; for (int i = 0; i < str.Length; i++) { // Look for quote if (str[i] == '\'') { // Already in quote? if (inQuote) { // See another single quote. Is this '' of 'fred''s' or '''', or is it an ending quote? if (i + 1 < str.Length && str[i + 1] == '\'') { // Found another ', so we have ''. Need to add \' instead. // 1st make sure we have our stringbuilder if (result == null) result = new StringBuilder(str, 0, i, str.Length * 2); // Append a \' and keep going (so we don't turn off quote mode) result.Append("\\'"); i++; continue; } // Turning off quote mode, fall through to add it inQuote = false; } else { // Found beginning quote, fall through to add it inQuote = true; } } // Is there a single \ character? else if (str[i] == '\\') { // Found a \, need to change it to \\ // 1st make sure we have our stringbuilder if (result == null) result = new StringBuilder(str, 0, i, str.Length * 2); // Append our \\ to the string & continue result.Append("\\\\"); continue; } // If we have a builder we need to add our character if (result != null) result.Append(str[i]); } // Unchanged string? , just return input string if (result == null) return str; // String changed, need to use the builder return result.ToString(); } private string[] GetMonthNames(CultureInfo ci, int calendar, uint calType) { string[] names = new string[13]; for (uint i = 0; i < 13; i++) { names[i] = GetCalendarInfo(ci, calendar, calType + i, false); } return names; } private int ConvertFirstDayOfWeekMonToSun(int iTemp) { // Convert Mon-Sun to Sun-Sat format iTemp++; if (iTemp > 6) { // Wrap Sunday and convert invalid data to Sunday iTemp = 0; } return iTemp; } private string[] GetDayNames(CultureInfo ci, int calendar, uint calType) { string[] names = new string[7]; for (uint i = 1; i < 7; i++) { names[i] = GetCalendarInfo(ci, calendar, calType + i - 1, true); } names[0] = GetCalendarInfo(ci, calendar, calType + 6, true); return names; } private int GetCalendarId(Calendar cal) { int calId = 0; if (cal is System.Globalization.GregorianCalendar) { calId = (int)(cal as GregorianCalendar).CalendarType; } else if (cal is System.Globalization.JapaneseCalendar) { calId = CAL_JAPAN; } else if (cal is System.Globalization.TaiwanCalendar) { calId = CAL_TAIWAN; } else if (cal is System.Globalization.KoreanCalendar) { calId = CAL_KOREA; } else if (cal is System.Globalization.HijriCalendar) { calId = CAL_HIJRI; } else if (cal is System.Globalization.ThaiBuddhistCalendar) { calId = CAL_THAI; } else if (cal is System.Globalization.HebrewCalendar) { calId = CAL_HEBREW; } else if (cal is System.Globalization.UmAlQuraCalendar) { calId = CAL_UMALQURA; } else if (cal is System.Globalization.PersianCalendar) { calId = CAL_PERSIAN; } else { throw new KeyNotFoundException(string.Format("Got a calendar {0} which we cannot map its Id", cal)); } return calId; } internal bool EnumLocales(string name, uint dwFlags, IntPtr param) { CultureInfo ci = new CultureInfo(name); if (!ci.IsNeutralCulture) cultures.Add(ci); return true; } private string GetLocaleInfo(CultureInfo ci, uint lctype) { Assert.True(GetLocaleInfoEx(ci.Name, lctype, sb, 400) > 0, string.Format("GetLocaleInfoEx failed when calling with lctype {0} and culture {1}", lctype, ci)); return sb.ToString(); } private string GetCalendarInfo(CultureInfo ci, int calendar, uint calType, bool throwInFail) { if (GetCalendarInfoEx(ci.Name, calendar, IntPtr.Zero, calType, sb, 400, IntPtr.Zero) <= 0) { Assert.False(throwInFail, string.Format("GetCalendarInfoEx failed when calling with caltype {0} and culture {1} and calendar Id {2}", calType, ci, calendar)); return ""; } return ReescapeWin32String(sb.ToString()); } private List<int> _optionalCals = new List<int>(); private bool EnumCalendarsCallback(string lpCalendarInfoString, int calendar, string pReserved, IntPtr lParam) { _optionalCals.Add(calendar); return true; } private int[] GetOptionalCalendars(CultureInfo ci) { _optionalCals = new List<int>(); Assert.True(EnumCalendarInfoExEx(EnumCalendarsCallback, ci.Name, ENUM_ALL_CALENDARS, null, CAL_ICALINTVALUE, IntPtr.Zero), "EnumCalendarInfoExEx has been failed."); return _optionalCals.ToArray(); } private List<string> _calPatterns; private bool EnumCalendarInfoCallback(string lpCalendarInfoString, int calendar, string pReserved, IntPtr lParam) { _calPatterns.Add(ReescapeWin32String(lpCalendarInfoString)); return true; } private string[] GetCalendarInfo(CultureInfo ci, int calId, uint calType) { _calPatterns = new List<string>(); Assert.True(EnumCalendarInfoExEx(EnumCalendarInfoCallback, ci.Name, (uint)calId, null, calType, IntPtr.Zero), "EnumCalendarInfoExEx has been failed in GetCalendarInfo."); return _calPatterns.ToArray(); } private int GetDefaultcalendar(CultureInfo ci) { int calId = GetLocaleInfoAsInt(ci, LOCALE_ICALENDARTYPE); if (calId != 0) return calId; int[] cals = GetOptionalCalendars(ci); Assert.True(cals.Length > 0); return cals[0]; } private int GetLocaleInfoAsInt(CultureInfo ci, uint lcType) { int data = 0; Assert.True(GetLocaleInfoEx(ci.Name, lcType | LOCALE_RETURN_NUMBER, ref data, sizeof(int)) > 0, string.Format("GetLocaleInfoEx failed with culture {0} and lcType {1}.", ci, lcType)); return data; } internal delegate bool EnumLocalesProcEx([MarshalAs(UnmanagedType.LPWStr)] string name, uint dwFlags, IntPtr param); internal delegate bool EnumCalendarInfoProcExEx([MarshalAs(UnmanagedType.LPWStr)] string lpCalendarInfoString, int Calendar, string lpReserved, IntPtr lParam); internal delegate bool EnumTimeFormatsProcEx([MarshalAs(UnmanagedType.LPWStr)] string lpTimeFormatString, IntPtr lParam); internal static StringBuilder sb = new StringBuilder(400); internal static List<CultureInfo> cultures = new List<CultureInfo>(); internal const uint LOCALE_WINDOWS = 0x00000001; internal const uint LOCALE_SENGLISHDISPLAYNAME = 0x00000072; internal const uint LOCALE_SNATIVEDISPLAYNAME = 0x00000073; internal const uint LOCALE_SPARENT = 0x0000006d; internal const uint LOCALE_SISO639LANGNAME = 0x00000059; internal const uint LOCALE_S1159 = 0x00000028; // AM designator, eg "AM" internal const uint LOCALE_S2359 = 0x00000029; // PM designator, eg "PM" internal const uint LOCALE_ICALENDARTYPE = 0x00001009; internal const uint LOCALE_RETURN_NUMBER = 0x20000000; internal const uint LOCALE_IFIRSTWEEKOFYEAR = 0x0000100D; internal const uint LOCALE_IFIRSTDAYOFWEEK = 0x0000100C; internal const uint LOCALE_SLONGDATE = 0x00000020; internal const uint LOCALE_STIMEFORMAT = 0x00001003; internal const uint LOCALE_RETURN_GENITIVE_NAMES = 0x10000000; internal const uint LOCALE_SSHORTDATE = 0x0000001F; internal const uint LOCALE_SSHORTTIME = 0x00000079; internal const uint LOCALE_SYEARMONTH = 0x00001006; internal const uint LOCALE_SPOSITIVESIGN = 0x00000050; // positive sign internal const uint LOCALE_SNEGATIVESIGN = 0x00000051; // negative sign internal const uint LOCALE_SDECIMAL = 0x0000000E; internal const uint LOCALE_STHOUSAND = 0x0000000F; internal const uint LOCALE_SMONTHOUSANDSEP = 0x00000017; internal const uint LOCALE_SMONDECIMALSEP = 0x00000016; internal const uint LOCALE_SCURRENCY = 0x00000014; internal const uint LOCALE_IDIGITS = 0x00000011; internal const uint LOCALE_ICURRDIGITS = 0x00000019; internal const uint LOCALE_ICURRENCY = 0x0000001B; internal const uint LOCALE_INEGCURR = 0x0000001C; internal const uint LOCALE_INEGNUMBER = 0x00001010; internal const uint LOCALE_SMONGROUPING = 0x00000018; internal const uint LOCALE_SNAN = 0x00000069; internal const uint LOCALE_SNEGINFINITY = 0x0000006b; // - Infinity internal const uint LOCALE_SGROUPING = 0x00000010; internal const uint LOCALE_INEGATIVEPERCENT = 0x00000074; internal const uint LOCALE_IPOSITIVEPERCENT = 0x00000075; internal const uint LOCALE_SPERCENT = 0x00000076; internal const uint LOCALE_SPERMILLE = 0x00000077; internal const uint LOCALE_SPOSINFINITY = 0x0000006a; internal const uint LOCALE_SENGLISHCOUNTRYNAME = 0x00001002; internal const uint LOCALE_IMEASURE = 0x0000000D; internal const uint LOCALE_SINTLSYMBOL = 0x00000015; internal const uint LOCALE_SISO3166CTRYNAME = 0x0000005A; internal const uint LOCALE_SNATIVECOUNTRYNAME = 0x00000008; internal const uint CAL_SABBREVDAYNAME1 = 0x0000000e; internal const uint CAL_SMONTHNAME1 = 0x00000015; internal const uint CAL_SABBREVMONTHNAME1 = 0x00000022; internal const uint CAL_ICALINTVALUE = 0x00000001; internal const uint CAL_SDAYNAME1 = 0x00000007; internal const uint CAL_SLONGDATE = 0x00000006; internal const uint CAL_SMONTHDAY = 0x00000038; internal const uint CAL_SSHORTDATE = 0x00000005; internal const uint CAL_SSHORTESTDAYNAME1 = 0x00000031; internal const uint CAL_SYEARMONTH = 0x0000002f; internal const uint CAL_SERASTRING = 0x00000004; internal const uint CAL_SABBREVERASTRING = 0x00000039; internal const uint ENUM_ALL_CALENDARS = 0xffffffff; internal const uint TIME_NOSECONDS = 0x00000002; internal const int CAL_JAPAN = 3; // Japanese Emperor Era calendar internal const int CAL_TAIWAN = 4; // Taiwan Era calendar internal const int CAL_KOREA = 5; // Korean Tangun Era calendar internal const int CAL_HIJRI = 6; // Hijri (Arabic Lunar) calendar internal const int CAL_THAI = 7; // Thai calendar internal const int CAL_HEBREW = 8; // Hebrew (Lunar) calendar internal const int CAL_PERSIAN = 22; internal const int CAL_UMALQURA = 23; [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal static extern int GetLocaleInfoEx(string lpLocaleName, uint LCType, StringBuilder data, int cchData); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal static extern int GetLocaleInfoEx(string lpLocaleName, uint LCType, ref int data, int cchData); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal static extern bool EnumSystemLocalesEx(EnumLocalesProcEx lpLocaleEnumProcEx, uint dwFlags, IntPtr lParam, IntPtr reserved); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal static extern int GetCalendarInfoEx(string lpLocaleName, int Calendar, IntPtr lpReserved, uint CalType, StringBuilder lpCalData, int cchData, IntPtr lpValue); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal static extern int GetCalendarInfoEx(string lpLocaleName, int Calendar, IntPtr lpReserved, uint CalType, StringBuilder lpCalData, int cchData, ref uint lpValue); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal static extern bool EnumCalendarInfoExEx(EnumCalendarInfoProcExEx pCalInfoEnumProcExEx, string lpLocaleName, uint Calendar, string lpReserved, uint CalType, IntPtr lParam); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal static extern bool EnumTimeFormatsEx(EnumTimeFormatsProcEx lpTimeFmtEnumProcEx, string lpLocaleName, uint dwFlags, IntPtr lParam); public static IEnumerable<object[]> CultureInfo_TestData() { yield return new object[] { 0x0001, new [] { "ar" }, "ar-SA", "ara", "ARA", "ar", "en-US" }; yield return new object[] { 0x0002, new [] { "bg" }, "bg-BG", "bul", "BGR", "bg", "bg-BG" }; yield return new object[] { 0x0003, new [] { "ca" }, "ca-ES", "cat", "CAT", "ca", "ca-ES" }; yield return new object[] { 0x0004, new [] { "zh-chs", "zh-hans" }, "zh-CN", "zho", "CHS", "zh-Hans", "zh-CN", true }; yield return new object[] { 0x0005, new [] { "cs" }, "cs-CZ", "ces", "CSY", "cs", "cs-CZ" }; yield return new object[] { 0x0006, new [] { "da" }, "da-DK", "dan", "DAN", "da", "da-DK" }; yield return new object[] { 0x0007, new [] { "de" }, "de-DE", "deu", "DEU", "de", "de-DE" }; yield return new object[] { 0x0008, new [] { "el" }, "el-GR", "ell", "ELL", "el", "el-GR" }; yield return new object[] { 0x0009, new [] { "en" }, "en-US", "eng", "ENU", "en", "en-US" }; yield return new object[] { 0x000a, new [] { "es" }, "es-ES", "spa", "ESP", "es", "es-ES" }; yield return new object[] { 0x000b, new [] { "fi" }, "fi-FI", "fin", "FIN", "fi", "fi-FI" }; yield return new object[] { 0x000c, new [] { "fr" }, "fr-FR", "fra", "FRA", "fr", "fr-FR" }; yield return new object[] { 0x000d, new [] { "he" }, "he-IL", "heb", "HEB", "he", "en-US" }; yield return new object[] { 0x000e, new [] { "hu" }, "hu-HU", "hun", "HUN", "hu", "hu-HU" }; yield return new object[] { 0x0010, new [] { "it" }, "it-IT", "ita", "ITA", "it", "it-IT" }; yield return new object[] { 0x0011, new [] { "ja" }, "ja-JP", "jpn", "JPN", "ja", "ja-JP" }; yield return new object[] { 0x0012, new [] { "ko" }, "ko-KR", "kor", "KOR", "ko", "ko-KR" }; yield return new object[] { 0x0013, new [] { "nl" }, "nl-NL", "nld", "NLD", "nl", "nl-NL" }; yield return new object[] { 0x0015, new [] { "pl" }, "pl-PL", "pol", "PLK", "pl", "pl-PL" }; yield return new object[] { 0x0016, new [] { "pt" }, "pt-BR", "por", "PTB", "pt", "pt-BR" }; yield return new object[] { 0x0018, new [] { "ro" }, "ro-RO", "ron", "ROM", "ro", "ro-RO" }; yield return new object[] { 0x0019, new [] { "ru" }, "ru-RU", "rus", "RUS", "ru", "ru-RU" }; yield return new object[] { 0x001a, new [] { "hr" }, "hr-HR", "hrv", "HRV", "hr", "hr-HR" }; yield return new object[] { 0x001b, new [] { "sk" }, "sk-SK", "slk", "SKY", "sk", "sk-SK" }; yield return new object[] { 0x001d, new [] { "sv" }, "sv-SE", "swe", "SVE", "sv", "sv-SE" }; yield return new object[] { 0x001e, new [] { "th" }, "th-TH", "tha", "THA", "th", "en-US" }; yield return new object[] { 0x001f, new [] { "tr" }, "tr-TR", "tur", "TRK", "tr", "tr-TR" }; yield return new object[] { 0x0021, new [] { "id" }, "id-ID", "ind", "IND", "id", "id-ID" }; yield return new object[] { 0x0022, new [] { "uk" }, "uk-UA", "ukr", "UKR", "uk", "uk-UA" }; yield return new object[] { 0x0024, new [] { "sl" }, "sl-SI", "slv", "SLV", "sl", "sl-SI" }; yield return new object[] { 0x0025, new [] { "et" }, "et-EE", "est", "ETI", "et", "et-EE" }; yield return new object[] { 0x0026, new [] { "lv" }, "lv-LV", "lav", "LVI", "lv", "lv-LV" }; yield return new object[] { 0x0027, new [] { "lt" }, "lt-LT", "lit", "LTH", "lt", "lt-LT" }; yield return new object[] { 0x0029, new [] { "fa" }, "fa-IR", "fas", "FAR", "fa", "en-US" }; yield return new object[] { 0x002a, new [] { "vi" }, "vi-VN", "vie", "VIT", "vi", "en-US" }; yield return new object[] { 0x0039, new [] { "hi" }, "hi-IN", "hin", "HIN", "hi", "en-US" }; yield return new object[] { 0x003e, new [] { "ms" }, "ms-MY", "msa", "MSL", "ms", "ms-MY" }; yield return new object[] { 0x0041, new [] { "sw" }, "sw-KE", "swa", "SWK", "sw", "sw-KE" }; yield return new object[] { 0x0047, new [] { "gu" }, "gu-IN", "guj", "GUJ", "gu", "en-US" }; yield return new object[] { 0x004a, new [] { "te" }, "te-IN", "tel", "TEL", "te", "en-US" }; yield return new object[] { 0x004b, new [] { "kn" }, "kn-IN", "kan", "KDI", "kn", "en-US" }; yield return new object[] { 0x004e, new [] { "mr" }, "mr-IN", "mar", "MAR", "mr", "en-US" }; yield return new object[] { 0x005e, new [] { "am" }, "am-ET", "amh", "AMH", "am", "en-US" }; yield return new object[] { 0x0401, new [] { "ar-sa" }, "ar-SA", "ara", "ARA", "ar-SA", "en-US" }; yield return new object[] { 0x0402, new [] { "bg-bg" }, "bg-BG", "bul", "BGR", "bg-BG", "bg-BG" }; yield return new object[] { 0x0403, new [] { "ca-es" }, "ca-ES", "cat", "CAT", "ca-ES", "ca-ES" }; yield return new object[] { 0x0404, new [] { "zh-tw" }, "zh-TW", "zho", "CHT", "zh-Hant-TW", "zh-TW" }; yield return new object[] { 0x0405, new [] { "cs-cz" }, "cs-CZ", "ces", "CSY", "cs-CZ", "cs-CZ" }; yield return new object[] { 0x0406, new [] { "da-dk" }, "da-DK", "dan", "DAN", "da-DK", "da-DK" }; yield return new object[] { 0x0407, new [] { "de-de" }, "de-DE", "deu", "DEU", "de-DE", "de-DE" }; yield return new object[] { 0x0408, new [] { "el-gr" }, "el-GR", "ell", "ELL", "el-GR", "el-GR" }; yield return new object[] { 0x0409, new [] { "en-us" }, "en-US", "eng", "ENU", "en-US", "en-US" }; yield return new object[] { 0x040b, new [] { "fi-fi" }, "fi-FI", "fin", "FIN", "fi-FI", "fi-FI" }; yield return new object[] { 0x040c, new [] { "fr-fr" }, "fr-FR", "fra", "FRA", "fr-FR", "fr-FR" }; yield return new object[] { 0x040d, new [] { "he-il" }, "he-IL", "heb", "HEB", "he-IL", "en-US" }; yield return new object[] { 0x040e, new [] { "hu-hu" }, "hu-HU", "hun", "HUN", "hu-HU", "hu-HU" }; yield return new object[] { 0x0410, new [] { "it-it" }, "it-IT", "ita", "ITA", "it-IT", "it-IT" }; yield return new object[] { 0x0411, new [] { "ja-jp" }, "ja-JP", "jpn", "JPN", "ja-JP", "ja-JP" }; yield return new object[] { 0x0412, new [] { "ko-kr" }, "ko-KR", "kor", "KOR", "ko-KR", "ko-KR" }; yield return new object[] { 0x0413, new [] { "nl-nl" }, "nl-NL", "nld", "NLD", "nl-NL", "nl-NL" }; yield return new object[] { 0x0415, new [] { "pl-pl" }, "pl-PL", "pol", "PLK", "pl-PL", "pl-PL" }; yield return new object[] { 0x0416, new [] { "pt-br" }, "pt-BR", "por", "PTB", "pt-BR", "pt-BR" }; yield return new object[] { 0x0418, new [] { "ro-ro" }, "ro-RO", "ron", "ROM", "ro-RO", "ro-RO" }; yield return new object[] { 0x0419, new [] { "ru-ru" }, "ru-RU", "rus", "RUS", "ru-RU", "ru-RU" }; yield return new object[] { 0x041a, new [] { "hr-hr" }, "hr-HR", "hrv", "HRV", "hr-HR", "hr-HR" }; yield return new object[] { 0x041b, new [] { "sk-sk" }, "sk-SK", "slk", "SKY", "sk-SK", "sk-SK" }; yield return new object[] { 0x041d, new [] { "sv-se" }, "sv-SE", "swe", "SVE", "sv-SE", "sv-SE" }; yield return new object[] { 0x041e, new [] { "th-th" }, "th-TH", "tha", "THA", "th-TH", "en-US" }; yield return new object[] { 0x041f, new [] { "tr-tr" }, "tr-TR", "tur", "TRK", "tr-TR", "tr-TR" }; yield return new object[] { 0x0421, new [] { "id-id" }, "id-ID", "ind", "IND", "id-ID", "id-ID" }; yield return new object[] { 0x0422, new [] { "uk-ua" }, "uk-UA", "ukr", "UKR", "uk-UA", "uk-UA" }; yield return new object[] { 0x0424, new [] { "sl-si" }, "sl-SI", "slv", "SLV", "sl-SI", "sl-SI" }; yield return new object[] { 0x0425, new [] { "et-ee" }, "et-EE", "est", "ETI", "et-EE", "et-EE" }; yield return new object[] { 0x0426, new [] { "lv-lv" }, "lv-LV", "lav", "LVI", "lv-LV", "lv-LV" }; yield return new object[] { 0x0427, new [] { "lt-lt" }, "lt-LT", "lit", "LTH", "lt-LT", "lt-LT" }; yield return new object[] { 0x0429, new [] { "fa-ir" }, "fa-IR", "fas", "FAR", "fa-IR", "en-US" }; yield return new object[] { 0x042a, new [] { "vi-vn" }, "vi-VN", "vie", "VIT", "vi-VN", "en-US" }; yield return new object[] { 0x0439, new [] { "hi-in" }, "hi-IN", "hin", "HIN", "hi-IN", "en-US" }; yield return new object[] { 0x0441, new [] { "sw-ke" }, "sw-KE", "swa", "SWK", "sw-KE", "sw-KE" }; yield return new object[] { 0x0447, new [] { "gu-in" }, "gu-IN", "guj", "GUJ", "gu-IN", "en-US" }; yield return new object[] { 0x044a, new [] { "te-in" }, "te-IN", "tel", "TEL", "te-IN", "en-US" }; yield return new object[] { 0x044b, new [] { "kn-in" }, "kn-IN", "kan", "KDI", "kn-IN", "en-US" }; yield return new object[] { 0x044e, new [] { "mr-in" }, "mr-IN", "mar", "MAR", "mr-IN", "en-US" }; yield return new object[] { 0x045e, new [] { "am-et" }, "am-ET", "amh", "AMH", "am-ET", "en-US" }; yield return new object[] { 0x0464, new [] { "fil-ph" }, "fil-PH", "fil", "FPO", "fil-PH", "fil-PH" }; yield return new object[] { 0x0804, new [] { "zh-cn" }, "zh-CN", "zho", "CHS", "zh-Hans-CN", "zh-CN" }; yield return new object[] { 0x0807, new [] { "de-ch" }, "de-CH", "deu", "DES", "de-CH", "de-CH" }; yield return new object[] { 0x0809, new [] { "en-gb" }, "en-GB", "eng", "ENG", "en-GB", "en-GB" }; yield return new object[] { 0x080a, new [] { "es-mx" }, "es-MX", "spa", "ESM", "es-MX", "es-MX" }; yield return new object[] { 0x080c, new [] { "fr-be" }, "fr-BE", "fra", "FRB", "fr-BE", "fr-BE" }; yield return new object[] { 0x0810, new [] { "it-ch" }, "it-CH", "ita", "ITS", "it-CH", "it-CH" }; yield return new object[] { 0x0813, new [] { "nl-be" }, "nl-BE", "nld", "NLB", "nl-BE", "nl-BE" }; yield return new object[] { 0x0816, new [] { "pt-pt" }, "pt-PT", "por", "PTG", "pt-PT", "pt-PT" }; yield return new object[] { 0x0c04, new [] { "zh-hk" }, "zh-HK", "zho", "ZHH", "zh-Hant-HK", "zh-HK" }; yield return new object[] { 0x0c07, new [] { "de-at" }, "de-AT", "deu", "DEA", "de-AT", "de-AT" }; yield return new object[] { 0x0c09, new [] { "en-au" }, "en-AU", "eng", "ENA", "en-AU", "en-AU" }; yield return new object[] { 0x0c0a, new [] { "es-es" }, "es-ES", "spa", "ESN", "es-ES", "es-ES" }; yield return new object[] { 0x0c0c, new [] { "fr-ca" }, "fr-CA", "fra", "FRC", "fr-CA", "fr-CA" }; yield return new object[] { 0x1004, new [] { "zh-sg" }, "zh-SG", "zho", "ZHI", "zh-Hans-SG", "zh-SG" }; yield return new object[] { 0x1007, new [] { "de-lu" }, "de-LU", "deu", "DEL", "de-LU", "de-LU" }; yield return new object[] { 0x1009, new [] { "en-ca" }, "en-CA", "eng", "ENC", "en-CA", "en-CA" }; yield return new object[] { 0x100c, new [] { "fr-ch" }, "fr-CH", "fra", "FRS", "fr-CH", "fr-CH" }; yield return new object[] { 0x1407, new [] { "de-li" }, "de-LI", "deu", "DEC", "de-LI", "de-LI" }; yield return new object[] { 0x1409, new [] { "en-nz" }, "en-NZ", "eng", "ENZ", "en-NZ", "en-NZ" }; yield return new object[] { 0x1809, new [] { "en-ie" }, "en-IE", "eng", "ENI", "en-IE", "en-IE" }; yield return new object[] { 0x1c09, new [] { "en-za" }, "en-ZA", "eng", "ENS", "en-ZA", "en-ZA" }; yield return new object[] { 0x2009, new [] { "en-jm" }, "en-JM", "eng", "ENJ", "en-JM", "en-JM" }; yield return new object[] { 0x241a, new [] { "sr-latn-rs" }, "sr-Latn-RS", "srp", "SRM", "sr-Latn-RS", "sr-Latn-RS" }; yield return new object[] { 0x2809, new [] { "en-bz" }, "en-BZ", "eng", "ENL", "en-BZ", "en-BZ" }; yield return new object[] { 0x281a, new [] { "sr-cyrl-rs" }, "sr-Cyrl-RS", "srp", "SRO", "sr-Cyrl-RS", "sr-Cyrl-RS" }; yield return new object[] { 0x2c09, new [] { "en-tt" }, "en-TT", "eng", "ENT", "en-TT", "en-TT" }; yield return new object[] { 0x3009, new [] { "en-zw" }, "en-ZW", "eng", "ENW", "en-ZW", "en-ZW" }; yield return new object[] { 0x3409, new [] { "en-ph" }, "en-PH", "eng", "ENP", "en-PH", "en-PH" }; yield return new object[] { 0x4009, new [] { "en-in" }, "en-IN", "eng", "ENN", "en-IN", "en-IN" }; yield return new object[] { 0x4809, new [] { "en-sg" }, "en-SG", "eng", "ENE", "en-SG", "en-SG" }; yield return new object[] { 0x6c1a, new [] { "sr-cyrl" }, "sr-Cyrl-RS", "srp", "SRO", "sr-Cyrl", "sr-Cyrl-RS" }; yield return new object[] { 0x701a, new [] { "sr-latn" }, "sr-Latn-RS", "srp", "SRM", "sr-Latn", "sr-Latn-RS" }; yield return new object[] { 0x7804, new [] { "zh" }, "zh-CN", "zho", "CHS", "zh", "zh-CN" }; yield return new object[] { 0x7c04, new [] { "zh-cht", "zh-hant" }, "zh-HK", "zho", "CHT", "zh-Hant", "zh-HK", true }; yield return new object[] { 0x7c1a, new [] { "sr" }, "sr-Latn-RS", "srp", "SRB", "sr", "sr-Latn-RS" }; yield return new object[] { 0x10407, new [] { "de-de_phoneb", "de-de" }, "de-DE", "deu", "DEU", "de-DE", "de-DE", true }; yield return new object[] { 0x1040e, new [] { "hu-hu_technl", "hu-hu" }, "hu-HU", "hun", "HUN", "hu-HU", "hu-HU", true }; yield return new object[] { 0x20804, new [] { "zh-cn_stroke", "zh-cn" }, "zh-CN", "zho", "CHS", "zh-Hans-CN", "zh-CN", true }; yield return new object[] { 0x21004, new [] { "zh-sg_stroke", "zh-sg" }, "zh-SG", "zho", "ZHI", "zh-Hans-SG", "zh-SG", true }; yield return new object[] { 0x30404, new [] { "zh-tw_pronun", "zh-tw" }, "zh-TW", "zho", "CHT", "zh-Hant-TW", "zh-TW", true }; yield return new object[] { 0x40404, new [] { "zh-tw_radstr", "zh-tw" }, "zh-TW", "zho", "CHT", "zh-Hant-TW", "zh-TW", true }; yield return new object[] { 0x40411, new [] { "ja-jp_radstr", "ja-jp" }, "ja-JP", "jpn", "JPN", "ja-JP", "ja-JP", true }; yield return new object[] { 0x40c04, new [] { "zh-hk_radstr", "zh-hk" }, "zh-HK", "zho", "ZHH", "zh-Hant-HK", "zh-HK", true }; } [Theory] [MemberData(nameof(CultureInfo_TestData))] public void LcidTest(int lcid, string[] cultureNames, string specificCultureName, string threeLetterISOLanguageName, string threeLetterWindowsLanguageName, string alternativeCultureName, string consoleUICultureName, bool expectToThrowOnBrowser = false) { if (!expectToThrowOnBrowser || PlatformDetection.IsNotBrowser) { _ = alternativeCultureName; CultureInfo ci = new CultureInfo(lcid); Assert.Contains(ci.Name, cultureNames, StringComparer.OrdinalIgnoreCase); Assert.True(lcid == ci.LCID || (ushort)lcid == (ushort)ci.LCID); Assert.True(ci.UseUserOverride, "UseUserOverride for lcid created culture expected to be true"); Assert.False(ci.IsReadOnly, "IsReadOnly for lcid created culture expected to be false"); if (ci.ThreeLetterISOLanguageName != "") { Assert.Equal(threeLetterISOLanguageName, ci.ThreeLetterISOLanguageName); } if (ci.ThreeLetterWindowsLanguageName != "ZZZ") { Assert.True((threeLetterWindowsLanguageName == ci.ThreeLetterWindowsLanguageName) || (threeLetterWindowsLanguageName == "CHT" && ci.ThreeLetterWindowsLanguageName == "ZHH")); } ci = new CultureInfo(cultureNames[0]); Assert.Contains(ci.Name, cultureNames, StringComparer.OrdinalIgnoreCase); Assert.True(lcid == ci.LCID || (ushort)lcid == (ushort)ci.LCID); Assert.True(ci.UseUserOverride, "UseUserOverride for named created culture expected to be true"); Assert.False(ci.IsReadOnly, "IsReadOnly for named created culture expected to be false"); ci = new CultureInfo(lcid, false); Assert.Contains(ci.Name, cultureNames, StringComparer.OrdinalIgnoreCase); Assert.True(lcid == ci.LCID || (ushort)lcid == (ushort)ci.LCID); Assert.False(ci.UseUserOverride, "UseUserOverride with false user override culture expected to be false"); Assert.False(ci.IsReadOnly, "IsReadOnly with false user override culture expected to be false"); ci = CultureInfo.GetCultureInfo(lcid); Assert.Contains(ci.Name, cultureNames, StringComparer.OrdinalIgnoreCase); Assert.True(lcid == ci.LCID || (ushort)lcid == (ushort)ci.LCID); Assert.False(ci.UseUserOverride, "UseUserOverride with Culture created by GetCultureInfo and lcid expected to be false"); Assert.True(ci.IsReadOnly, "IsReadOnly with Culture created by GetCultureInfo and lcid expected to be true"); ci = CultureInfo.GetCultureInfo(cultureNames[0]); Assert.Contains(ci.Name, cultureNames, StringComparer.OrdinalIgnoreCase); Assert.True(lcid == ci.LCID || (ushort)lcid == (ushort)ci.LCID); Assert.False(ci.UseUserOverride, "UseUserOverride with Culture created by GetCultureInfo and name expected to be false"); Assert.True(ci.IsReadOnly, "IsReadOnly with Culture created by GetCultureInfo and name expected to be true"); ci = CultureInfo.GetCultureInfo(cultureNames[0], ""); Assert.Contains(ci.Name, cultureNames, StringComparer.OrdinalIgnoreCase); Assert.True(lcid == ci.LCID || (ushort)lcid == (ushort)ci.LCID); Assert.False(ci.UseUserOverride, "UseUserOverride with Culture created by GetCultureInfo and sort name expected to be false"); Assert.True(ci.IsReadOnly, "IsReadOnly with Culture created by GetCultureInfo and sort name expected to be true"); Assert.Equal(CultureInfo.InvariantCulture.TextInfo, ci.TextInfo); Assert.Equal(CultureInfo.InvariantCulture.CompareInfo, ci.CompareInfo); ci = CultureInfo.CreateSpecificCulture(cultureNames[0]); TestCultureName(specificCultureName, ci.Name); // CultureInfo.GetCultureInfoByIetfLanguageTag doesn't support alternative sort LCID's. if (lcid <= 0xffff && lcid != 0x040a) { ci = CultureInfo.GetCultureInfoByIetfLanguageTag(cultureNames[0]); Assert.Contains(ci.Name, cultureNames, StringComparer.OrdinalIgnoreCase); TestCultureName(ci.Name, ci.IetfLanguageTag); Assert.True(lcid == ci.KeyboardLayoutId || (ushort)lcid == (ushort)ci.KeyboardLayoutId); } if (ci.GetConsoleFallbackUICulture().Name != "") { Assert.Equal(consoleUICultureName, ci.GetConsoleFallbackUICulture().Name); } } else { AssertExtensions.Throws<CultureNotFoundException>(() => new CultureInfo(lcid)); } } private static string[] hans = new[] { "zh-CN", "zh-CHS", "zh-Hans" }; private static string[] hant = new[] { "zh-HK", "zh-CHT", "zh-Hant" }; private static void TestCultureName(string left, string right) { if (hans.Contains(left, StringComparer.OrdinalIgnoreCase)) { Assert.Contains(right, hans, StringComparer.OrdinalIgnoreCase); } else if (hant.Contains(left, StringComparer.OrdinalIgnoreCase)) { Assert.Contains(right, hant, StringComparer.OrdinalIgnoreCase); } else { Assert.Equal(left, right, ignoreCase: true); } } [Fact] public void InstalledUICultureTest() { var c1 = CultureInfo.InstalledUICulture; var c2 = CultureInfo.InstalledUICulture; // we cannot expect the value we get for InstalledUICulture without reading the OS. // instead we test ensuring the value doesn't change if we requested it multiple times. Assert.Equal(c1.Name, c2.Name); } [Theory] [MemberData(nameof(CultureInfo_TestData))] public void GetCulturesTest(int lcid, string[] cultureNames, string specificCultureName, string threeLetterISOLanguageName, string threeLetterWindowsLanguageName, string alternativeCultureName, string consoleUICultureName, bool expectToThrowOnBrowser = false) { if (!expectToThrowOnBrowser || PlatformDetection.IsNotBrowser) { _ = lcid; _ = specificCultureName; _ = threeLetterISOLanguageName; _ = threeLetterWindowsLanguageName; _ = consoleUICultureName; bool found = false; Assert.All(CultureInfo.GetCultures(CultureTypes.NeutralCultures), c => Assert.True( (c.IsNeutralCulture && ((c.CultureTypes & CultureTypes.NeutralCultures) != 0)) || c.Equals(CultureInfo.InvariantCulture))); found = CultureInfo.GetCultures(CultureTypes.NeutralCultures).Any(c => cultureNames.Contains(c.Name, StringComparer.OrdinalIgnoreCase) || c.Name.Equals(alternativeCultureName, StringComparison.OrdinalIgnoreCase)); Assert.All(CultureInfo.GetCultures(CultureTypes.SpecificCultures), c => Assert.True(!c.IsNeutralCulture && ((c.CultureTypes & CultureTypes.SpecificCultures) != 0))); if (!found) { found = CultureInfo.GetCultures(CultureTypes.SpecificCultures).Any(c => cultureNames.Contains(c.Name, StringComparer.OrdinalIgnoreCase) || c.Name.Equals(alternativeCultureName, StringComparison.OrdinalIgnoreCase)); } Assert.True(found, $"Expected to find the culture {cultureNames[0]} in the enumerated list"); } else { AssertExtensions.Throws<CultureNotFoundException>(() => new CultureInfo(lcid)); } } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public void ClearCachedDataTest() { RemoteExecutor.Invoke(() => { CultureInfo ci = CultureInfo.GetCultureInfo("ja-JP"); Assert.True((object) ci == (object) CultureInfo.GetCultureInfo("ja-JP"), "Expected getting same object reference"); ci.ClearCachedData(); Assert.False((object) ci == (object) CultureInfo.GetCultureInfo("ja-JP"), "expected to get a new object reference"); }).Dispose(); } [Fact] public void CultureNotFoundExceptionTest() { AssertExtensions.Throws<CultureNotFoundException>("name", () => new CultureInfo("!@#$%^&*()")); AssertExtensions.Throws<CultureNotFoundException>("name", () => new CultureInfo("This is invalid culture")); AssertExtensions.Throws<CultureNotFoundException>("name", () => new CultureInfo("longCulture" + new string('a', 100))); AssertExtensions.Throws<CultureNotFoundException>("culture", () => new CultureInfo(0x1000)); CultureNotFoundException e = AssertExtensions.Throws<CultureNotFoundException>("name", () => new CultureInfo("This is invalid culture")); Assert.Equal("This is invalid culture", e.InvalidCultureName); e = AssertExtensions.Throws<CultureNotFoundException>("culture", () => new CultureInfo(0x1000)); Assert.Equal(0x1000, e.InvalidCultureId); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using Microsoft.DotNet.RemoteExecutor; using System.Text; using System.Diagnostics; using Xunit; namespace System.Globalization.Tests { public class CultureInfoAll { [PlatformSpecific(TestPlatforms.Windows)] // P/Invoke to Win32 function [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNlsGlobalization))] public void TestAllCultures_Nls() { Assert.True(EnumSystemLocalesEx(EnumLocales, LOCALE_WINDOWS, IntPtr.Zero, IntPtr.Zero), "EnumSystemLocalesEx has failed"); Assert.All(cultures, Validate); } private void Validate(CultureInfo ci) { Assert.Equal(ci.EnglishName, GetLocaleInfo(ci, LOCALE_SENGLISHDISPLAYNAME)); // si-LK has some special case when running on Win7 so we just ignore this one if (!ci.Name.Equals("si-LK", StringComparison.OrdinalIgnoreCase)) { Assert.Equal(ci.Name.Length == 0 ? "Invariant Language (Invariant Country)" : GetLocaleInfo(ci, LOCALE_SNATIVEDISPLAYNAME), ci.NativeName); } // zh-Hans and zh-Hant has different behavior on different platform Assert.Contains(GetLocaleInfo(ci, LOCALE_SPARENT), new[] { "zh-Hans", "zh-Hant", ci.Parent.Name }, StringComparer.OrdinalIgnoreCase); Assert.Equal(ci.TwoLetterISOLanguageName, GetLocaleInfo(ci, LOCALE_SISO639LANGNAME)); ValidateDTFI(ci); ValidateNFI(ci); ValidateRegionInfo(ci); } private void ValidateDTFI(CultureInfo ci) { DateTimeFormatInfo dtfi = ci.DateTimeFormat; Calendar cal = dtfi.Calendar; int calId = GetCalendarId(cal); Assert.Equal(GetDayNames(ci, calId, CAL_SABBREVDAYNAME1), dtfi.AbbreviatedDayNames); Assert.Equal(GetDayNames(ci, calId, CAL_SDAYNAME1), dtfi.DayNames); Assert.Equal(GetMonthNames(ci, calId, CAL_SMONTHNAME1), dtfi.MonthNames); Assert.Equal(GetMonthNames(ci, calId, CAL_SABBREVMONTHNAME1), dtfi.AbbreviatedMonthNames); Assert.Equal(GetMonthNames(ci, calId, CAL_SMONTHNAME1 | LOCALE_RETURN_GENITIVE_NAMES), dtfi.MonthGenitiveNames); Assert.Equal(GetMonthNames(ci, calId, CAL_SABBREVMONTHNAME1 | LOCALE_RETURN_GENITIVE_NAMES), dtfi.AbbreviatedMonthGenitiveNames); Assert.Equal(GetDayNames(ci, calId, CAL_SSHORTESTDAYNAME1), dtfi.ShortestDayNames); Assert.Equal(GetLocaleInfo(ci, LOCALE_S1159), dtfi.AMDesignator, StringComparer.OrdinalIgnoreCase); Assert.Equal(GetLocaleInfo(ci, LOCALE_S2359), dtfi.PMDesignator, StringComparer.OrdinalIgnoreCase); Assert.Equal(calId, GetDefaultcalendar(ci)); Assert.Equal((int)dtfi.FirstDayOfWeek, ConvertFirstDayOfWeekMonToSun(GetLocaleInfoAsInt(ci, LOCALE_IFIRSTDAYOFWEEK))); Assert.Equal((int)dtfi.CalendarWeekRule, GetLocaleInfoAsInt(ci, LOCALE_IFIRSTWEEKOFYEAR)); Assert.Equal(dtfi.MonthDayPattern, GetCalendarInfo(ci, calId, CAL_SMONTHDAY, true)); Assert.Equal("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", dtfi.RFC1123Pattern); Assert.Equal("yyyy'-'MM'-'dd'T'HH':'mm':'ss", dtfi.SortableDateTimePattern); Assert.Equal("yyyy'-'MM'-'dd HH':'mm':'ss'Z'", dtfi.UniversalSortableDateTimePattern); string longDatePattern1 = GetCalendarInfo(ci, calId, CAL_SLONGDATE)[0]; string longDatePattern2 = ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SLONGDATE)); string longTimePattern1 = GetTimeFormats(ci, 0)[0]; string longTimePattern2 = ReescapeWin32String(GetLocaleInfo(ci, LOCALE_STIMEFORMAT)); string fullDateTimePattern = longDatePattern1 + " " + longTimePattern1; string fullDateTimePattern1 = longDatePattern2 + " " + longTimePattern2; Assert.Contains(dtfi.FullDateTimePattern, new[] { fullDateTimePattern, fullDateTimePattern1 }); Assert.Contains(dtfi.LongDatePattern, new[] { longDatePattern1, longDatePattern2 }); Assert.Contains(dtfi.LongTimePattern, new[] { longTimePattern1, longTimePattern2 }); Assert.Contains(dtfi.ShortTimePattern, new[] { GetTimeFormats(ci, TIME_NOSECONDS)[0], ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SSHORTTIME)) }); Assert.Contains(dtfi.ShortDatePattern, new[] { GetCalendarInfo(ci, calId, CAL_SSHORTDATE)[0], ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SSHORTDATE)) }); Assert.Contains(dtfi.YearMonthPattern, new[] { GetCalendarInfo(ci, calId, CAL_SYEARMONTH)[0], ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SYEARMONTH)) }); int eraNameIndex = 1; Assert.All(GetCalendarInfo(ci, calId, CAL_SERASTRING), eraName => Assert.Equal(dtfi.GetEraName(eraNameIndex++), eraName, StringComparer.OrdinalIgnoreCase)); eraNameIndex = 1; Assert.All(GetCalendarInfo(ci, calId, CAL_SABBREVERASTRING), eraName => Assert.Equal(dtfi.GetAbbreviatedEraName(eraNameIndex++), eraName, StringComparer.OrdinalIgnoreCase)); } private void ValidateNFI(CultureInfo ci) { NumberFormatInfo nfi = ci.NumberFormat; Assert.Equal(string.IsNullOrEmpty(GetLocaleInfo(ci, LOCALE_SPOSITIVESIGN)) ? "+" : GetLocaleInfo(ci, LOCALE_SPOSITIVESIGN), nfi.PositiveSign); Assert.Equal(GetLocaleInfo(ci, LOCALE_SNEGATIVESIGN), nfi.NegativeSign); Assert.Equal(GetLocaleInfo(ci, LOCALE_SDECIMAL), nfi.NumberDecimalSeparator); Assert.Equal(GetLocaleInfo(ci, LOCALE_SDECIMAL), nfi.PercentDecimalSeparator); Assert.Equal(GetLocaleInfo(ci, LOCALE_STHOUSAND), nfi.NumberGroupSeparator); Assert.Equal(GetLocaleInfo(ci, LOCALE_STHOUSAND), nfi.PercentGroupSeparator); Assert.Equal(GetLocaleInfo(ci, LOCALE_SMONTHOUSANDSEP), nfi.CurrencyGroupSeparator); Assert.Equal(GetLocaleInfo(ci, LOCALE_SMONDECIMALSEP), nfi.CurrencyDecimalSeparator); Assert.Equal(GetLocaleInfo(ci, LOCALE_SCURRENCY), nfi.CurrencySymbol); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IDIGITS), nfi.NumberDecimalDigits); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IDIGITS), nfi.PercentDecimalDigits); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_ICURRDIGITS), nfi.CurrencyDecimalDigits); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_ICURRENCY), nfi.CurrencyPositivePattern); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_INEGCURR), nfi.CurrencyNegativePattern); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_INEGNUMBER), nfi.NumberNegativePattern); Assert.Equal(ConvertWin32GroupString(GetLocaleInfo(ci, LOCALE_SMONGROUPING)), nfi.CurrencyGroupSizes); Assert.Equal(GetLocaleInfo(ci, LOCALE_SNAN), nfi.NaNSymbol); Assert.Equal(GetLocaleInfo(ci, LOCALE_SNEGINFINITY), nfi.NegativeInfinitySymbol); Assert.Equal(ConvertWin32GroupString(GetLocaleInfo(ci, LOCALE_SGROUPING)), nfi.NumberGroupSizes); Assert.Equal(ConvertWin32GroupString(GetLocaleInfo(ci, LOCALE_SGROUPING)), nfi.PercentGroupSizes); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_INEGATIVEPERCENT), nfi.PercentNegativePattern); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IPOSITIVEPERCENT), nfi.PercentPositivePattern); Assert.Equal(GetLocaleInfo(ci, LOCALE_SPERCENT), nfi.PercentSymbol); Assert.Equal(GetLocaleInfo(ci, LOCALE_SPERMILLE), nfi.PerMilleSymbol); Assert.Equal(GetLocaleInfo(ci, LOCALE_SPOSINFINITY), nfi.PositiveInfinitySymbol); } private void ValidateRegionInfo(CultureInfo ci) { if (ci.Name.Length == 0) // no region for invariant return; RegionInfo ri = new RegionInfo(ci.Name); Assert.Equal(GetLocaleInfo(ci, LOCALE_SCURRENCY), ri.CurrencySymbol); Assert.Equal(GetLocaleInfo(ci, LOCALE_SENGLISHCOUNTRYNAME), ri.EnglishName); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IMEASURE) == 0, ri.IsMetric); Assert.Equal(GetLocaleInfo(ci, LOCALE_SINTLSYMBOL), ri.ISOCurrencySymbol); Assert.True(ci.Name.Equals(ri.Name, StringComparison.OrdinalIgnoreCase) || // Desktop usese culture name as region name ri.Name.Equals(GetLocaleInfo(ci, LOCALE_SISO3166CTRYNAME), StringComparison.OrdinalIgnoreCase)); // netcore uses 2 letter ISO for region name Assert.Equal(GetLocaleInfo(ci, LOCALE_SISO3166CTRYNAME), ri.TwoLetterISORegionName, StringComparer.OrdinalIgnoreCase); Assert.Equal(GetLocaleInfo(ci, LOCALE_SNATIVECOUNTRYNAME), ri.NativeName, StringComparer.OrdinalIgnoreCase); } private int[] ConvertWin32GroupString(string win32Str) { // None of these cases make any sense if (win32Str == null || win32Str.Length == 0) { return (new int[] { 3 }); } if (win32Str[0] == '0') { return (new int[] { 0 }); } // Since its in n;n;n;n;n format, we can always get the length quickly int[] values; if (win32Str[win32Str.Length - 1] == '0') { // Trailing 0 gets dropped. 1;0 -> 1 values = new int[(win32Str.Length / 2)]; } else { // Need extra space for trailing zero 1 -> 1;0 values = new int[(win32Str.Length / 2) + 2]; values[values.Length - 1] = 0; } int i; int j; for (i = 0, j = 0; i < win32Str.Length && j < values.Length; i += 2, j++) { // Note that this # shouldn't ever be zero, 'cause 0 is only at end // But we'll test because its registry that could be anything if (win32Str[i] < '1' || win32Str[i] > '9') return new int[] { 3 }; values[j] = (int)(win32Str[i] - '0'); } return (values); } private List<string> _timePatterns; private bool EnumTimeFormats(string lpTimeFormatString, IntPtr lParam) { _timePatterns.Add(ReescapeWin32String(lpTimeFormatString)); return true; } private string[] GetTimeFormats(CultureInfo ci, uint flags) { _timePatterns = new List<string>(); Assert.True(EnumTimeFormatsEx(EnumTimeFormats, ci.Name, flags, IntPtr.Zero), string.Format("EnumTimeFormatsEx failed with culture {0} and flags {1}", ci, flags)); return _timePatterns.ToArray(); } internal string ReescapeWin32String(string str) { // If we don't have data, then don't try anything if (str == null) return null; StringBuilder result = null; bool inQuote = false; for (int i = 0; i < str.Length; i++) { // Look for quote if (str[i] == '\'') { // Already in quote? if (inQuote) { // See another single quote. Is this '' of 'fred''s' or '''', or is it an ending quote? if (i + 1 < str.Length && str[i + 1] == '\'') { // Found another ', so we have ''. Need to add \' instead. // 1st make sure we have our stringbuilder if (result == null) result = new StringBuilder(str, 0, i, str.Length * 2); // Append a \' and keep going (so we don't turn off quote mode) result.Append("\\'"); i++; continue; } // Turning off quote mode, fall through to add it inQuote = false; } else { // Found beginning quote, fall through to add it inQuote = true; } } // Is there a single \ character? else if (str[i] == '\\') { // Found a \, need to change it to \\ // 1st make sure we have our stringbuilder if (result == null) result = new StringBuilder(str, 0, i, str.Length * 2); // Append our \\ to the string & continue result.Append("\\\\"); continue; } // If we have a builder we need to add our character if (result != null) result.Append(str[i]); } // Unchanged string? , just return input string if (result == null) return str; // String changed, need to use the builder return result.ToString(); } private string[] GetMonthNames(CultureInfo ci, int calendar, uint calType) { string[] names = new string[13]; for (uint i = 0; i < 13; i++) { names[i] = GetCalendarInfo(ci, calendar, calType + i, false); } return names; } private int ConvertFirstDayOfWeekMonToSun(int iTemp) { // Convert Mon-Sun to Sun-Sat format iTemp++; if (iTemp > 6) { // Wrap Sunday and convert invalid data to Sunday iTemp = 0; } return iTemp; } private string[] GetDayNames(CultureInfo ci, int calendar, uint calType) { string[] names = new string[7]; for (uint i = 1; i < 7; i++) { names[i] = GetCalendarInfo(ci, calendar, calType + i - 1, true); } names[0] = GetCalendarInfo(ci, calendar, calType + 6, true); return names; } private int GetCalendarId(Calendar cal) { int calId = 0; if (cal is System.Globalization.GregorianCalendar) { calId = (int)(cal as GregorianCalendar).CalendarType; } else if (cal is System.Globalization.JapaneseCalendar) { calId = CAL_JAPAN; } else if (cal is System.Globalization.TaiwanCalendar) { calId = CAL_TAIWAN; } else if (cal is System.Globalization.KoreanCalendar) { calId = CAL_KOREA; } else if (cal is System.Globalization.HijriCalendar) { calId = CAL_HIJRI; } else if (cal is System.Globalization.ThaiBuddhistCalendar) { calId = CAL_THAI; } else if (cal is System.Globalization.HebrewCalendar) { calId = CAL_HEBREW; } else if (cal is System.Globalization.UmAlQuraCalendar) { calId = CAL_UMALQURA; } else if (cal is System.Globalization.PersianCalendar) { calId = CAL_PERSIAN; } else { throw new KeyNotFoundException(string.Format("Got a calendar {0} which we cannot map its Id", cal)); } return calId; } internal bool EnumLocales(string name, uint dwFlags, IntPtr param) { CultureInfo ci = new CultureInfo(name); if (!ci.IsNeutralCulture) cultures.Add(ci); return true; } private string GetLocaleInfo(CultureInfo ci, uint lctype) { Assert.True(GetLocaleInfoEx(ci.Name, lctype, sb, 400) > 0, string.Format("GetLocaleInfoEx failed when calling with lctype {0} and culture {1}", lctype, ci)); return sb.ToString(); } private string GetCalendarInfo(CultureInfo ci, int calendar, uint calType, bool throwInFail) { if (GetCalendarInfoEx(ci.Name, calendar, IntPtr.Zero, calType, sb, 400, IntPtr.Zero) <= 0) { Assert.False(throwInFail, string.Format("GetCalendarInfoEx failed when calling with caltype {0} and culture {1} and calendar Id {2}", calType, ci, calendar)); return ""; } return ReescapeWin32String(sb.ToString()); } private List<int> _optionalCals = new List<int>(); private bool EnumCalendarsCallback(string lpCalendarInfoString, int calendar, string pReserved, IntPtr lParam) { _optionalCals.Add(calendar); return true; } private int[] GetOptionalCalendars(CultureInfo ci) { _optionalCals = new List<int>(); Assert.True(EnumCalendarInfoExEx(EnumCalendarsCallback, ci.Name, ENUM_ALL_CALENDARS, null, CAL_ICALINTVALUE, IntPtr.Zero), "EnumCalendarInfoExEx has been failed."); return _optionalCals.ToArray(); } private List<string> _calPatterns; private bool EnumCalendarInfoCallback(string lpCalendarInfoString, int calendar, string pReserved, IntPtr lParam) { _calPatterns.Add(ReescapeWin32String(lpCalendarInfoString)); return true; } private string[] GetCalendarInfo(CultureInfo ci, int calId, uint calType) { _calPatterns = new List<string>(); Assert.True(EnumCalendarInfoExEx(EnumCalendarInfoCallback, ci.Name, (uint)calId, null, calType, IntPtr.Zero), "EnumCalendarInfoExEx has been failed in GetCalendarInfo."); return _calPatterns.ToArray(); } private int GetDefaultcalendar(CultureInfo ci) { int calId = GetLocaleInfoAsInt(ci, LOCALE_ICALENDARTYPE); if (calId != 0) return calId; int[] cals = GetOptionalCalendars(ci); Assert.True(cals.Length > 0); return cals[0]; } private int GetLocaleInfoAsInt(CultureInfo ci, uint lcType) { int data = 0; Assert.True(GetLocaleInfoEx(ci.Name, lcType | LOCALE_RETURN_NUMBER, ref data, sizeof(int)) > 0, string.Format("GetLocaleInfoEx failed with culture {0} and lcType {1}.", ci, lcType)); return data; } internal delegate bool EnumLocalesProcEx([MarshalAs(UnmanagedType.LPWStr)] string name, uint dwFlags, IntPtr param); internal delegate bool EnumCalendarInfoProcExEx([MarshalAs(UnmanagedType.LPWStr)] string lpCalendarInfoString, int Calendar, string lpReserved, IntPtr lParam); internal delegate bool EnumTimeFormatsProcEx([MarshalAs(UnmanagedType.LPWStr)] string lpTimeFormatString, IntPtr lParam); internal static StringBuilder sb = new StringBuilder(400); internal static List<CultureInfo> cultures = new List<CultureInfo>(); internal const uint LOCALE_WINDOWS = 0x00000001; internal const uint LOCALE_SENGLISHDISPLAYNAME = 0x00000072; internal const uint LOCALE_SNATIVEDISPLAYNAME = 0x00000073; internal const uint LOCALE_SPARENT = 0x0000006d; internal const uint LOCALE_SISO639LANGNAME = 0x00000059; internal const uint LOCALE_S1159 = 0x00000028; // AM designator, eg "AM" internal const uint LOCALE_S2359 = 0x00000029; // PM designator, eg "PM" internal const uint LOCALE_ICALENDARTYPE = 0x00001009; internal const uint LOCALE_RETURN_NUMBER = 0x20000000; internal const uint LOCALE_IFIRSTWEEKOFYEAR = 0x0000100D; internal const uint LOCALE_IFIRSTDAYOFWEEK = 0x0000100C; internal const uint LOCALE_SLONGDATE = 0x00000020; internal const uint LOCALE_STIMEFORMAT = 0x00001003; internal const uint LOCALE_RETURN_GENITIVE_NAMES = 0x10000000; internal const uint LOCALE_SSHORTDATE = 0x0000001F; internal const uint LOCALE_SSHORTTIME = 0x00000079; internal const uint LOCALE_SYEARMONTH = 0x00001006; internal const uint LOCALE_SPOSITIVESIGN = 0x00000050; // positive sign internal const uint LOCALE_SNEGATIVESIGN = 0x00000051; // negative sign internal const uint LOCALE_SDECIMAL = 0x0000000E; internal const uint LOCALE_STHOUSAND = 0x0000000F; internal const uint LOCALE_SMONTHOUSANDSEP = 0x00000017; internal const uint LOCALE_SMONDECIMALSEP = 0x00000016; internal const uint LOCALE_SCURRENCY = 0x00000014; internal const uint LOCALE_IDIGITS = 0x00000011; internal const uint LOCALE_ICURRDIGITS = 0x00000019; internal const uint LOCALE_ICURRENCY = 0x0000001B; internal const uint LOCALE_INEGCURR = 0x0000001C; internal const uint LOCALE_INEGNUMBER = 0x00001010; internal const uint LOCALE_SMONGROUPING = 0x00000018; internal const uint LOCALE_SNAN = 0x00000069; internal const uint LOCALE_SNEGINFINITY = 0x0000006b; // - Infinity internal const uint LOCALE_SGROUPING = 0x00000010; internal const uint LOCALE_INEGATIVEPERCENT = 0x00000074; internal const uint LOCALE_IPOSITIVEPERCENT = 0x00000075; internal const uint LOCALE_SPERCENT = 0x00000076; internal const uint LOCALE_SPERMILLE = 0x00000077; internal const uint LOCALE_SPOSINFINITY = 0x0000006a; internal const uint LOCALE_SENGLISHCOUNTRYNAME = 0x00001002; internal const uint LOCALE_IMEASURE = 0x0000000D; internal const uint LOCALE_SINTLSYMBOL = 0x00000015; internal const uint LOCALE_SISO3166CTRYNAME = 0x0000005A; internal const uint LOCALE_SNATIVECOUNTRYNAME = 0x00000008; internal const uint CAL_SABBREVDAYNAME1 = 0x0000000e; internal const uint CAL_SMONTHNAME1 = 0x00000015; internal const uint CAL_SABBREVMONTHNAME1 = 0x00000022; internal const uint CAL_ICALINTVALUE = 0x00000001; internal const uint CAL_SDAYNAME1 = 0x00000007; internal const uint CAL_SLONGDATE = 0x00000006; internal const uint CAL_SMONTHDAY = 0x00000038; internal const uint CAL_SSHORTDATE = 0x00000005; internal const uint CAL_SSHORTESTDAYNAME1 = 0x00000031; internal const uint CAL_SYEARMONTH = 0x0000002f; internal const uint CAL_SERASTRING = 0x00000004; internal const uint CAL_SABBREVERASTRING = 0x00000039; internal const uint ENUM_ALL_CALENDARS = 0xffffffff; internal const uint TIME_NOSECONDS = 0x00000002; internal const int CAL_JAPAN = 3; // Japanese Emperor Era calendar internal const int CAL_TAIWAN = 4; // Taiwan Era calendar internal const int CAL_KOREA = 5; // Korean Tangun Era calendar internal const int CAL_HIJRI = 6; // Hijri (Arabic Lunar) calendar internal const int CAL_THAI = 7; // Thai calendar internal const int CAL_HEBREW = 8; // Hebrew (Lunar) calendar internal const int CAL_PERSIAN = 22; internal const int CAL_UMALQURA = 23; [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal static extern int GetLocaleInfoEx(string lpLocaleName, uint LCType, StringBuilder data, int cchData); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal static extern int GetLocaleInfoEx(string lpLocaleName, uint LCType, ref int data, int cchData); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal static extern bool EnumSystemLocalesEx(EnumLocalesProcEx lpLocaleEnumProcEx, uint dwFlags, IntPtr lParam, IntPtr reserved); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal static extern int GetCalendarInfoEx(string lpLocaleName, int Calendar, IntPtr lpReserved, uint CalType, StringBuilder lpCalData, int cchData, IntPtr lpValue); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal static extern int GetCalendarInfoEx(string lpLocaleName, int Calendar, IntPtr lpReserved, uint CalType, StringBuilder lpCalData, int cchData, ref uint lpValue); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal static extern bool EnumCalendarInfoExEx(EnumCalendarInfoProcExEx pCalInfoEnumProcExEx, string lpLocaleName, uint Calendar, string lpReserved, uint CalType, IntPtr lParam); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal static extern bool EnumTimeFormatsEx(EnumTimeFormatsProcEx lpTimeFmtEnumProcEx, string lpLocaleName, uint dwFlags, IntPtr lParam); public static IEnumerable<object[]> CultureInfo_TestData() { yield return new object[] { 0x0001, new [] { "ar" }, "ar-SA", "ara", "ARA", "ar", "en-US" }; yield return new object[] { 0x0002, new [] { "bg" }, "bg-BG", "bul", "BGR", "bg", "bg-BG" }; yield return new object[] { 0x0003, new [] { "ca" }, "ca-ES", "cat", "CAT", "ca", "ca-ES" }; yield return new object[] { 0x0004, new [] { "zh-chs", "zh-hans" }, "zh-CN", "zho", "CHS", "zh-Hans", "zh-CN", true }; yield return new object[] { 0x0005, new [] { "cs" }, "cs-CZ", "ces", "CSY", "cs", "cs-CZ" }; yield return new object[] { 0x0006, new [] { "da" }, "da-DK", "dan", "DAN", "da", "da-DK" }; yield return new object[] { 0x0007, new [] { "de" }, "de-DE", "deu", "DEU", "de", "de-DE" }; yield return new object[] { 0x0008, new [] { "el" }, "el-GR", "ell", "ELL", "el", "el-GR" }; yield return new object[] { 0x0009, new [] { "en" }, "en-US", "eng", "ENU", "en", "en-US" }; yield return new object[] { 0x000a, new [] { "es" }, "es-ES", "spa", "ESP", "es", "es-ES" }; yield return new object[] { 0x000b, new [] { "fi" }, "fi-FI", "fin", "FIN", "fi", "fi-FI" }; yield return new object[] { 0x000c, new [] { "fr" }, "fr-FR", "fra", "FRA", "fr", "fr-FR" }; yield return new object[] { 0x000d, new [] { "he" }, "he-IL", "heb", "HEB", "he", "en-US" }; yield return new object[] { 0x000e, new [] { "hu" }, "hu-HU", "hun", "HUN", "hu", "hu-HU" }; yield return new object[] { 0x0010, new [] { "it" }, "it-IT", "ita", "ITA", "it", "it-IT" }; yield return new object[] { 0x0011, new [] { "ja" }, "ja-JP", "jpn", "JPN", "ja", "ja-JP" }; yield return new object[] { 0x0012, new [] { "ko" }, "ko-KR", "kor", "KOR", "ko", "ko-KR" }; yield return new object[] { 0x0013, new [] { "nl" }, "nl-NL", "nld", "NLD", "nl", "nl-NL" }; yield return new object[] { 0x0015, new [] { "pl" }, "pl-PL", "pol", "PLK", "pl", "pl-PL" }; yield return new object[] { 0x0016, new [] { "pt" }, "pt-BR", "por", "PTB", "pt", "pt-BR" }; yield return new object[] { 0x0018, new [] { "ro" }, "ro-RO", "ron", "ROM", "ro", "ro-RO" }; yield return new object[] { 0x0019, new [] { "ru" }, "ru-RU", "rus", "RUS", "ru", "ru-RU" }; yield return new object[] { 0x001a, new [] { "hr" }, "hr-HR", "hrv", "HRV", "hr", "hr-HR" }; yield return new object[] { 0x001b, new [] { "sk" }, "sk-SK", "slk", "SKY", "sk", "sk-SK" }; yield return new object[] { 0x001d, new [] { "sv" }, "sv-SE", "swe", "SVE", "sv", "sv-SE" }; yield return new object[] { 0x001e, new [] { "th" }, "th-TH", "tha", "THA", "th", "en-US" }; yield return new object[] { 0x001f, new [] { "tr" }, "tr-TR", "tur", "TRK", "tr", "tr-TR" }; yield return new object[] { 0x0021, new [] { "id" }, "id-ID", "ind", "IND", "id", "id-ID" }; yield return new object[] { 0x0022, new [] { "uk" }, "uk-UA", "ukr", "UKR", "uk", "uk-UA" }; yield return new object[] { 0x0024, new [] { "sl" }, "sl-SI", "slv", "SLV", "sl", "sl-SI" }; yield return new object[] { 0x0025, new [] { "et" }, "et-EE", "est", "ETI", "et", "et-EE" }; yield return new object[] { 0x0026, new [] { "lv" }, "lv-LV", "lav", "LVI", "lv", "lv-LV" }; yield return new object[] { 0x0027, new [] { "lt" }, "lt-LT", "lit", "LTH", "lt", "lt-LT" }; yield return new object[] { 0x0029, new [] { "fa" }, "fa-IR", "fas", "FAR", "fa", "en-US" }; yield return new object[] { 0x002a, new [] { "vi" }, "vi-VN", "vie", "VIT", "vi", "en-US" }; yield return new object[] { 0x0039, new [] { "hi" }, "hi-IN", "hin", "HIN", "hi", "en-US" }; yield return new object[] { 0x003e, new [] { "ms" }, "ms-MY", "msa", "MSL", "ms", "ms-MY" }; yield return new object[] { 0x0041, new [] { "sw" }, "sw-KE", "swa", "SWK", "sw", "sw-KE" }; yield return new object[] { 0x0047, new [] { "gu" }, "gu-IN", "guj", "GUJ", "gu", "en-US" }; yield return new object[] { 0x004a, new [] { "te" }, "te-IN", "tel", "TEL", "te", "en-US" }; yield return new object[] { 0x004b, new [] { "kn" }, "kn-IN", "kan", "KDI", "kn", "en-US" }; yield return new object[] { 0x004e, new [] { "mr" }, "mr-IN", "mar", "MAR", "mr", "en-US" }; yield return new object[] { 0x005e, new [] { "am" }, "am-ET", "amh", "AMH", "am", "en-US" }; yield return new object[] { 0x0401, new [] { "ar-sa" }, "ar-SA", "ara", "ARA", "ar-SA", "en-US" }; yield return new object[] { 0x0402, new [] { "bg-bg" }, "bg-BG", "bul", "BGR", "bg-BG", "bg-BG" }; yield return new object[] { 0x0403, new [] { "ca-es" }, "ca-ES", "cat", "CAT", "ca-ES", "ca-ES" }; yield return new object[] { 0x0404, new [] { "zh-tw" }, "zh-TW", "zho", "CHT", "zh-Hant-TW", "zh-TW" }; yield return new object[] { 0x0405, new [] { "cs-cz" }, "cs-CZ", "ces", "CSY", "cs-CZ", "cs-CZ" }; yield return new object[] { 0x0406, new [] { "da-dk" }, "da-DK", "dan", "DAN", "da-DK", "da-DK" }; yield return new object[] { 0x0407, new [] { "de-de" }, "de-DE", "deu", "DEU", "de-DE", "de-DE" }; yield return new object[] { 0x0408, new [] { "el-gr" }, "el-GR", "ell", "ELL", "el-GR", "el-GR" }; yield return new object[] { 0x0409, new [] { "en-us" }, "en-US", "eng", "ENU", "en-US", "en-US" }; yield return new object[] { 0x040b, new [] { "fi-fi" }, "fi-FI", "fin", "FIN", "fi-FI", "fi-FI" }; yield return new object[] { 0x040c, new [] { "fr-fr" }, "fr-FR", "fra", "FRA", "fr-FR", "fr-FR" }; yield return new object[] { 0x040d, new [] { "he-il" }, "he-IL", "heb", "HEB", "he-IL", "en-US" }; yield return new object[] { 0x040e, new [] { "hu-hu" }, "hu-HU", "hun", "HUN", "hu-HU", "hu-HU" }; yield return new object[] { 0x0410, new [] { "it-it" }, "it-IT", "ita", "ITA", "it-IT", "it-IT" }; yield return new object[] { 0x0411, new [] { "ja-jp" }, "ja-JP", "jpn", "JPN", "ja-JP", "ja-JP" }; yield return new object[] { 0x0412, new [] { "ko-kr" }, "ko-KR", "kor", "KOR", "ko-KR", "ko-KR" }; yield return new object[] { 0x0413, new [] { "nl-nl" }, "nl-NL", "nld", "NLD", "nl-NL", "nl-NL" }; yield return new object[] { 0x0415, new [] { "pl-pl" }, "pl-PL", "pol", "PLK", "pl-PL", "pl-PL" }; yield return new object[] { 0x0416, new [] { "pt-br" }, "pt-BR", "por", "PTB", "pt-BR", "pt-BR" }; yield return new object[] { 0x0418, new [] { "ro-ro" }, "ro-RO", "ron", "ROM", "ro-RO", "ro-RO" }; yield return new object[] { 0x0419, new [] { "ru-ru" }, "ru-RU", "rus", "RUS", "ru-RU", "ru-RU" }; yield return new object[] { 0x041a, new [] { "hr-hr" }, "hr-HR", "hrv", "HRV", "hr-HR", "hr-HR" }; yield return new object[] { 0x041b, new [] { "sk-sk" }, "sk-SK", "slk", "SKY", "sk-SK", "sk-SK" }; yield return new object[] { 0x041d, new [] { "sv-se" }, "sv-SE", "swe", "SVE", "sv-SE", "sv-SE" }; yield return new object[] { 0x041e, new [] { "th-th" }, "th-TH", "tha", "THA", "th-TH", "en-US" }; yield return new object[] { 0x041f, new [] { "tr-tr" }, "tr-TR", "tur", "TRK", "tr-TR", "tr-TR" }; yield return new object[] { 0x0421, new [] { "id-id" }, "id-ID", "ind", "IND", "id-ID", "id-ID" }; yield return new object[] { 0x0422, new [] { "uk-ua" }, "uk-UA", "ukr", "UKR", "uk-UA", "uk-UA" }; yield return new object[] { 0x0424, new [] { "sl-si" }, "sl-SI", "slv", "SLV", "sl-SI", "sl-SI" }; yield return new object[] { 0x0425, new [] { "et-ee" }, "et-EE", "est", "ETI", "et-EE", "et-EE" }; yield return new object[] { 0x0426, new [] { "lv-lv" }, "lv-LV", "lav", "LVI", "lv-LV", "lv-LV" }; yield return new object[] { 0x0427, new [] { "lt-lt" }, "lt-LT", "lit", "LTH", "lt-LT", "lt-LT" }; yield return new object[] { 0x0429, new [] { "fa-ir" }, "fa-IR", "fas", "FAR", "fa-IR", "en-US" }; yield return new object[] { 0x042a, new [] { "vi-vn" }, "vi-VN", "vie", "VIT", "vi-VN", "en-US" }; yield return new object[] { 0x0439, new [] { "hi-in" }, "hi-IN", "hin", "HIN", "hi-IN", "en-US" }; yield return new object[] { 0x0441, new [] { "sw-ke" }, "sw-KE", "swa", "SWK", "sw-KE", "sw-KE" }; yield return new object[] { 0x0447, new [] { "gu-in" }, "gu-IN", "guj", "GUJ", "gu-IN", "en-US" }; yield return new object[] { 0x044a, new [] { "te-in" }, "te-IN", "tel", "TEL", "te-IN", "en-US" }; yield return new object[] { 0x044b, new [] { "kn-in" }, "kn-IN", "kan", "KDI", "kn-IN", "en-US" }; yield return new object[] { 0x044e, new [] { "mr-in" }, "mr-IN", "mar", "MAR", "mr-IN", "en-US" }; yield return new object[] { 0x045e, new [] { "am-et" }, "am-ET", "amh", "AMH", "am-ET", "en-US" }; yield return new object[] { 0x0464, new [] { "fil-ph" }, "fil-PH", "fil", "FPO", "fil-PH", "fil-PH" }; yield return new object[] { 0x0804, new [] { "zh-cn" }, "zh-CN", "zho", "CHS", "zh-Hans-CN", "zh-CN" }; yield return new object[] { 0x0807, new [] { "de-ch" }, "de-CH", "deu", "DES", "de-CH", "de-CH" }; yield return new object[] { 0x0809, new [] { "en-gb" }, "en-GB", "eng", "ENG", "en-GB", "en-GB" }; yield return new object[] { 0x080a, new [] { "es-mx" }, "es-MX", "spa", "ESM", "es-MX", "es-MX" }; yield return new object[] { 0x080c, new [] { "fr-be" }, "fr-BE", "fra", "FRB", "fr-BE", "fr-BE" }; yield return new object[] { 0x0810, new [] { "it-ch" }, "it-CH", "ita", "ITS", "it-CH", "it-CH" }; yield return new object[] { 0x0813, new [] { "nl-be" }, "nl-BE", "nld", "NLB", "nl-BE", "nl-BE" }; yield return new object[] { 0x0816, new [] { "pt-pt" }, "pt-PT", "por", "PTG", "pt-PT", "pt-PT" }; yield return new object[] { 0x0c04, new [] { "zh-hk" }, "zh-HK", "zho", "ZHH", "zh-Hant-HK", "zh-HK" }; yield return new object[] { 0x0c07, new [] { "de-at" }, "de-AT", "deu", "DEA", "de-AT", "de-AT" }; yield return new object[] { 0x0c09, new [] { "en-au" }, "en-AU", "eng", "ENA", "en-AU", "en-AU" }; yield return new object[] { 0x0c0a, new [] { "es-es" }, "es-ES", "spa", "ESN", "es-ES", "es-ES" }; yield return new object[] { 0x0c0c, new [] { "fr-ca" }, "fr-CA", "fra", "FRC", "fr-CA", "fr-CA" }; yield return new object[] { 0x1004, new [] { "zh-sg" }, "zh-SG", "zho", "ZHI", "zh-Hans-SG", "zh-SG" }; yield return new object[] { 0x1007, new [] { "de-lu" }, "de-LU", "deu", "DEL", "de-LU", "de-LU" }; yield return new object[] { 0x1009, new [] { "en-ca" }, "en-CA", "eng", "ENC", "en-CA", "en-CA" }; yield return new object[] { 0x100c, new [] { "fr-ch" }, "fr-CH", "fra", "FRS", "fr-CH", "fr-CH" }; yield return new object[] { 0x1407, new [] { "de-li" }, "de-LI", "deu", "DEC", "de-LI", "de-LI" }; yield return new object[] { 0x1409, new [] { "en-nz" }, "en-NZ", "eng", "ENZ", "en-NZ", "en-NZ" }; yield return new object[] { 0x1809, new [] { "en-ie" }, "en-IE", "eng", "ENI", "en-IE", "en-IE" }; yield return new object[] { 0x1c09, new [] { "en-za" }, "en-ZA", "eng", "ENS", "en-ZA", "en-ZA" }; yield return new object[] { 0x2009, new [] { "en-jm" }, "en-JM", "eng", "ENJ", "en-JM", "en-JM" }; yield return new object[] { 0x241a, new [] { "sr-latn-rs" }, "sr-Latn-RS", "srp", "SRM", "sr-Latn-RS", "sr-Latn-RS" }; yield return new object[] { 0x2809, new [] { "en-bz" }, "en-BZ", "eng", "ENL", "en-BZ", "en-BZ" }; yield return new object[] { 0x281a, new [] { "sr-cyrl-rs" }, "sr-Cyrl-RS", "srp", "SRO", "sr-Cyrl-RS", "sr-Cyrl-RS" }; yield return new object[] { 0x2c09, new [] { "en-tt" }, "en-TT", "eng", "ENT", "en-TT", "en-TT" }; yield return new object[] { 0x3009, new [] { "en-zw" }, "en-ZW", "eng", "ENW", "en-ZW", "en-ZW" }; yield return new object[] { 0x3409, new [] { "en-ph" }, "en-PH", "eng", "ENP", "en-PH", "en-PH" }; yield return new object[] { 0x4009, new [] { "en-in" }, "en-IN", "eng", "ENN", "en-IN", "en-IN" }; yield return new object[] { 0x4809, new [] { "en-sg" }, "en-SG", "eng", "ENE", "en-SG", "en-SG" }; yield return new object[] { 0x6c1a, new [] { "sr-cyrl" }, "sr-Cyrl-RS", "srp", "SRO", "sr-Cyrl", "sr-Cyrl-RS" }; yield return new object[] { 0x701a, new [] { "sr-latn" }, "sr-Latn-RS", "srp", "SRM", "sr-Latn", "sr-Latn-RS" }; yield return new object[] { 0x7804, new [] { "zh" }, "zh-CN", "zho", "CHS", "zh", "zh-CN" }; yield return new object[] { 0x7c04, new [] { "zh-cht", "zh-hant" }, "zh-HK", "zho", "CHT", "zh-Hant", "zh-HK", true }; yield return new object[] { 0x7c1a, new [] { "sr" }, "sr-Latn-RS", "srp", "SRB", "sr", "sr-Latn-RS" }; yield return new object[] { 0x10407, new [] { "de-de_phoneb", "de-de" }, "de-DE", "deu", "DEU", "de-DE", "de-DE", true }; yield return new object[] { 0x1040e, new [] { "hu-hu_technl", "hu-hu" }, "hu-HU", "hun", "HUN", "hu-HU", "hu-HU", true }; yield return new object[] { 0x20804, new [] { "zh-cn_stroke", "zh-cn" }, "zh-CN", "zho", "CHS", "zh-Hans-CN", "zh-CN", true }; yield return new object[] { 0x21004, new [] { "zh-sg_stroke", "zh-sg" }, "zh-SG", "zho", "ZHI", "zh-Hans-SG", "zh-SG", true }; yield return new object[] { 0x30404, new [] { "zh-tw_pronun", "zh-tw" }, "zh-TW", "zho", "CHT", "zh-Hant-TW", "zh-TW", true }; yield return new object[] { 0x40404, new [] { "zh-tw_radstr", "zh-tw" }, "zh-TW", "zho", "CHT", "zh-Hant-TW", "zh-TW", true }; yield return new object[] { 0x40411, new [] { "ja-jp_radstr", "ja-jp" }, "ja-JP", "jpn", "JPN", "ja-JP", "ja-JP", true }; yield return new object[] { 0x40c04, new [] { "zh-hk_radstr", "zh-hk" }, "zh-HK", "zho", "ZHH", "zh-Hant-HK", "zh-HK", true }; } [Theory] [MemberData(nameof(CultureInfo_TestData))] public void LcidTest(int lcid, string[] cultureNames, string specificCultureName, string threeLetterISOLanguageName, string threeLetterWindowsLanguageName, string alternativeCultureName, string consoleUICultureName, bool expectToThrowOnBrowser = false) { if (!expectToThrowOnBrowser || PlatformDetection.IsNotBrowser) { _ = alternativeCultureName; CultureInfo ci = new CultureInfo(lcid); Assert.Contains(ci.Name, cultureNames, StringComparer.OrdinalIgnoreCase); Assert.True(lcid == ci.LCID || (ushort)lcid == (ushort)ci.LCID); Assert.True(ci.UseUserOverride, "UseUserOverride for lcid created culture expected to be true"); Assert.False(ci.IsReadOnly, "IsReadOnly for lcid created culture expected to be false"); if (ci.ThreeLetterISOLanguageName != "") { Assert.Equal(threeLetterISOLanguageName, ci.ThreeLetterISOLanguageName); } if (ci.ThreeLetterWindowsLanguageName != "ZZZ") { Assert.True((threeLetterWindowsLanguageName == ci.ThreeLetterWindowsLanguageName) || (threeLetterWindowsLanguageName == "CHT" && ci.ThreeLetterWindowsLanguageName == "ZHH")); } ci = new CultureInfo(cultureNames[0]); Assert.Contains(ci.Name, cultureNames, StringComparer.OrdinalIgnoreCase); Assert.True(lcid == ci.LCID || (ushort)lcid == (ushort)ci.LCID); Assert.True(ci.UseUserOverride, "UseUserOverride for named created culture expected to be true"); Assert.False(ci.IsReadOnly, "IsReadOnly for named created culture expected to be false"); ci = new CultureInfo(lcid, false); Assert.Contains(ci.Name, cultureNames, StringComparer.OrdinalIgnoreCase); Assert.True(lcid == ci.LCID || (ushort)lcid == (ushort)ci.LCID); Assert.False(ci.UseUserOverride, "UseUserOverride with false user override culture expected to be false"); Assert.False(ci.IsReadOnly, "IsReadOnly with false user override culture expected to be false"); ci = CultureInfo.GetCultureInfo(lcid); Assert.Contains(ci.Name, cultureNames, StringComparer.OrdinalIgnoreCase); Assert.True(lcid == ci.LCID || (ushort)lcid == (ushort)ci.LCID); Assert.False(ci.UseUserOverride, "UseUserOverride with Culture created by GetCultureInfo and lcid expected to be false"); Assert.True(ci.IsReadOnly, "IsReadOnly with Culture created by GetCultureInfo and lcid expected to be true"); ci = CultureInfo.GetCultureInfo(cultureNames[0]); Assert.Contains(ci.Name, cultureNames, StringComparer.OrdinalIgnoreCase); Assert.True(lcid == ci.LCID || (ushort)lcid == (ushort)ci.LCID); Assert.False(ci.UseUserOverride, "UseUserOverride with Culture created by GetCultureInfo and name expected to be false"); Assert.True(ci.IsReadOnly, "IsReadOnly with Culture created by GetCultureInfo and name expected to be true"); ci = CultureInfo.GetCultureInfo(cultureNames[0], ""); Assert.Contains(ci.Name, cultureNames, StringComparer.OrdinalIgnoreCase); Assert.True(lcid == ci.LCID || (ushort)lcid == (ushort)ci.LCID); Assert.False(ci.UseUserOverride, "UseUserOverride with Culture created by GetCultureInfo and sort name expected to be false"); Assert.True(ci.IsReadOnly, "IsReadOnly with Culture created by GetCultureInfo and sort name expected to be true"); Assert.Equal(CultureInfo.InvariantCulture.TextInfo, ci.TextInfo); Assert.Equal(CultureInfo.InvariantCulture.CompareInfo, ci.CompareInfo); ci = CultureInfo.CreateSpecificCulture(cultureNames[0]); TestCultureName(specificCultureName, ci.Name); // CultureInfo.GetCultureInfoByIetfLanguageTag doesn't support alternative sort LCID's. if (lcid <= 0xffff && lcid != 0x040a) { ci = CultureInfo.GetCultureInfoByIetfLanguageTag(cultureNames[0]); Assert.Contains(ci.Name, cultureNames, StringComparer.OrdinalIgnoreCase); TestCultureName(ci.Name, ci.IetfLanguageTag); Assert.True(lcid == ci.KeyboardLayoutId || (ushort)lcid == (ushort)ci.KeyboardLayoutId); } if (ci.GetConsoleFallbackUICulture().Name != "") { Assert.Equal(consoleUICultureName, ci.GetConsoleFallbackUICulture().Name); } } else { AssertExtensions.Throws<CultureNotFoundException>(() => new CultureInfo(lcid)); } } private static string[] hans = new[] { "zh-CN", "zh-CHS", "zh-Hans" }; private static string[] hant = new[] { "zh-HK", "zh-CHT", "zh-Hant" }; private static void TestCultureName(string left, string right) { if (hans.Contains(left, StringComparer.OrdinalIgnoreCase)) { Assert.Contains(right, hans, StringComparer.OrdinalIgnoreCase); } else if (hant.Contains(left, StringComparer.OrdinalIgnoreCase)) { Assert.Contains(right, hant, StringComparer.OrdinalIgnoreCase); } else { Assert.Equal(left, right, ignoreCase: true); } } [Fact] public void InstalledUICultureTest() { var c1 = CultureInfo.InstalledUICulture; var c2 = CultureInfo.InstalledUICulture; // we cannot expect the value we get for InstalledUICulture without reading the OS. // instead we test ensuring the value doesn't change if we requested it multiple times. Assert.Equal(c1.Name, c2.Name); } [Theory] [MemberData(nameof(CultureInfo_TestData))] public void GetCulturesTest(int lcid, string[] cultureNames, string specificCultureName, string threeLetterISOLanguageName, string threeLetterWindowsLanguageName, string alternativeCultureName, string consoleUICultureName, bool expectToThrowOnBrowser = false) { if (!expectToThrowOnBrowser || PlatformDetection.IsNotBrowser) { _ = lcid; _ = specificCultureName; _ = threeLetterISOLanguageName; _ = threeLetterWindowsLanguageName; _ = consoleUICultureName; bool found = false; Assert.All(CultureInfo.GetCultures(CultureTypes.NeutralCultures), c => Assert.True( (c.IsNeutralCulture && ((c.CultureTypes & CultureTypes.NeutralCultures) != 0)) || c.Equals(CultureInfo.InvariantCulture))); found = CultureInfo.GetCultures(CultureTypes.NeutralCultures).Any(c => cultureNames.Contains(c.Name, StringComparer.OrdinalIgnoreCase) || c.Name.Equals(alternativeCultureName, StringComparison.OrdinalIgnoreCase)); Assert.All(CultureInfo.GetCultures(CultureTypes.SpecificCultures), c => Assert.True(!c.IsNeutralCulture && ((c.CultureTypes & CultureTypes.SpecificCultures) != 0))); if (!found) { found = CultureInfo.GetCultures(CultureTypes.SpecificCultures).Any(c => cultureNames.Contains(c.Name, StringComparer.OrdinalIgnoreCase) || c.Name.Equals(alternativeCultureName, StringComparison.OrdinalIgnoreCase)); } Assert.True(found, $"Expected to find the culture {cultureNames[0]} in the enumerated list"); } else { AssertExtensions.Throws<CultureNotFoundException>(() => new CultureInfo(lcid)); } } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public void ClearCachedDataTest() { RemoteExecutor.Invoke(() => { CultureInfo ci = CultureInfo.GetCultureInfo("ja-JP"); Assert.True((object) ci == (object) CultureInfo.GetCultureInfo("ja-JP"), "Expected getting same object reference"); ci.ClearCachedData(); Assert.False((object) ci == (object) CultureInfo.GetCultureInfo("ja-JP"), "expected to get a new object reference"); }).Dispose(); } [Fact] public void CultureNotFoundExceptionTest() { AssertExtensions.Throws<CultureNotFoundException>("name", () => new CultureInfo("!@#$%^&*()")); AssertExtensions.Throws<CultureNotFoundException>("name", () => new CultureInfo("This is invalid culture")); AssertExtensions.Throws<CultureNotFoundException>("name", () => new CultureInfo("longCulture" + new string('a', 100))); AssertExtensions.Throws<CultureNotFoundException>("culture", () => new CultureInfo(0x1000)); CultureNotFoundException e = AssertExtensions.Throws<CultureNotFoundException>("name", () => new CultureInfo("This is invalid culture")); Assert.Equal("This is invalid culture", e.InvalidCultureName); e = AssertExtensions.Throws<CultureNotFoundException>("culture", () => new CultureInfo(0x1000)); Assert.Equal(0x1000, e.InvalidCultureId); } } }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/tests/JIT/CodeGenBringUpTests/DivConst_ro.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="DivConst.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="DivConst.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/ShiftRightLogical.Vector128.UInt64.1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void ShiftRightLogical_Vector128_UInt64_1() { var test = new ImmUnaryOpTest__ShiftRightLogical_Vector128_UInt64_1(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmUnaryOpTest__ShiftRightLogical_Vector128_UInt64_1 { private struct DataTable { private byte[] inArray; private byte[] outArray; private GCHandle inHandle; private GCHandle outHandle; private ulong alignment; public DataTable(UInt64[] inArray, UInt64[] outArray, int alignment) { int sizeOfinArray = inArray.Length * Unsafe.SizeOf<UInt64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle = GCHandle.Alloc(this.inArray, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArrayPtr), ref Unsafe.As<UInt64, byte>(ref inArray[0]), (uint)sizeOfinArray); } public void* inArrayPtr => Align((byte*)(inHandle.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<UInt64> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogical_Vector128_UInt64_1 testClass) { var result = AdvSimd.ShiftRightLogical(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmUnaryOpTest__ShiftRightLogical_Vector128_UInt64_1 testClass) { fixed (Vector128<UInt64>* pFld = &_fld) { var result = AdvSimd.ShiftRightLogical( AdvSimd.LoadVector128((UInt64*)(pFld)), 1 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static readonly byte Imm = 1; private static UInt64[] _data = new UInt64[Op1ElementCount]; private static Vector128<UInt64> _clsVar; private Vector128<UInt64> _fld; private DataTable _dataTable; static ImmUnaryOpTest__ShiftRightLogical_Vector128_UInt64_1() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); } public ImmUnaryOpTest__ShiftRightLogical_Vector128_UInt64_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); } _dataTable = new DataTable(_data, new UInt64[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.ShiftRightLogical( Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.ShiftRightLogical( AdvSimd.LoadVector128((UInt64*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftRightLogical), new Type[] { typeof(Vector128<UInt64>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftRightLogical), new Type[] { typeof(Vector128<UInt64>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((UInt64*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftRightLogical( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt64>* pClsVar = &_clsVar) { var result = AdvSimd.ShiftRightLogical( AdvSimd.LoadVector128((UInt64*)(pClsVar)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr); var result = AdvSimd.ShiftRightLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArrayPtr)); var result = AdvSimd.ShiftRightLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftRightLogical_Vector128_UInt64_1(); var result = AdvSimd.ShiftRightLogical(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmUnaryOpTest__ShiftRightLogical_Vector128_UInt64_1(); fixed (Vector128<UInt64>* pFld = &test._fld) { var result = AdvSimd.ShiftRightLogical( AdvSimd.LoadVector128((UInt64*)(pFld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftRightLogical(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt64>* pFld = &_fld) { var result = AdvSimd.ShiftRightLogical( AdvSimd.LoadVector128((UInt64*)(pFld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.ShiftRightLogical(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.ShiftRightLogical( AdvSimd.LoadVector128((UInt64*)(&test._fld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<UInt64> firstOp, void* result, [CallerMemberName] string method = "") { UInt64[] inArray = new UInt64[Op1ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { UInt64[] inArray = new UInt64[Op1ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(UInt64[] firstOp, UInt64[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftRightLogical(firstOp[i], Imm) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftRightLogical)}<UInt64>(Vector128<UInt64>, 1): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void ShiftRightLogical_Vector128_UInt64_1() { var test = new ImmUnaryOpTest__ShiftRightLogical_Vector128_UInt64_1(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmUnaryOpTest__ShiftRightLogical_Vector128_UInt64_1 { private struct DataTable { private byte[] inArray; private byte[] outArray; private GCHandle inHandle; private GCHandle outHandle; private ulong alignment; public DataTable(UInt64[] inArray, UInt64[] outArray, int alignment) { int sizeOfinArray = inArray.Length * Unsafe.SizeOf<UInt64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle = GCHandle.Alloc(this.inArray, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArrayPtr), ref Unsafe.As<UInt64, byte>(ref inArray[0]), (uint)sizeOfinArray); } public void* inArrayPtr => Align((byte*)(inHandle.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<UInt64> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogical_Vector128_UInt64_1 testClass) { var result = AdvSimd.ShiftRightLogical(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmUnaryOpTest__ShiftRightLogical_Vector128_UInt64_1 testClass) { fixed (Vector128<UInt64>* pFld = &_fld) { var result = AdvSimd.ShiftRightLogical( AdvSimd.LoadVector128((UInt64*)(pFld)), 1 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static readonly byte Imm = 1; private static UInt64[] _data = new UInt64[Op1ElementCount]; private static Vector128<UInt64> _clsVar; private Vector128<UInt64> _fld; private DataTable _dataTable; static ImmUnaryOpTest__ShiftRightLogical_Vector128_UInt64_1() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); } public ImmUnaryOpTest__ShiftRightLogical_Vector128_UInt64_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); } _dataTable = new DataTable(_data, new UInt64[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.ShiftRightLogical( Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.ShiftRightLogical( AdvSimd.LoadVector128((UInt64*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftRightLogical), new Type[] { typeof(Vector128<UInt64>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftRightLogical), new Type[] { typeof(Vector128<UInt64>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((UInt64*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftRightLogical( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt64>* pClsVar = &_clsVar) { var result = AdvSimd.ShiftRightLogical( AdvSimd.LoadVector128((UInt64*)(pClsVar)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr); var result = AdvSimd.ShiftRightLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArrayPtr)); var result = AdvSimd.ShiftRightLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftRightLogical_Vector128_UInt64_1(); var result = AdvSimd.ShiftRightLogical(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmUnaryOpTest__ShiftRightLogical_Vector128_UInt64_1(); fixed (Vector128<UInt64>* pFld = &test._fld) { var result = AdvSimd.ShiftRightLogical( AdvSimd.LoadVector128((UInt64*)(pFld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftRightLogical(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt64>* pFld = &_fld) { var result = AdvSimd.ShiftRightLogical( AdvSimd.LoadVector128((UInt64*)(pFld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.ShiftRightLogical(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.ShiftRightLogical( AdvSimd.LoadVector128((UInt64*)(&test._fld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<UInt64> firstOp, void* result, [CallerMemberName] string method = "") { UInt64[] inArray = new UInt64[Op1ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { UInt64[] inArray = new UInt64[Op1ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(UInt64[] firstOp, UInt64[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftRightLogical(firstOp[i], Imm) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftRightLogical)}<UInt64>(Vector128<UInt64>, 1): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b58358/b58358.il
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern legacy library mscorlib {} .assembly extern System.Console { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) .ver 4:0:0:0 } .assembly 'b58358' {} .assembly extern xunit.core {} .class ILGEN_0x493230e7 { .method static int32 Method_0x2d7c921() { .maxstack 11 ldc.r4 float32(0x6ef1549c) call float64 [mscorlib]System.Math::Sin(float64) ldc.r8 4.4 bgt Branch_0x2 ldc.i4 0xe br Branch_0x3 Branch_0x2: ldc.i4.6 Branch_0x3: ldc.i4.8 ble.un Branch_0x0 br Branch_0x1 Branch_0x0: ldc.i4.8 ldc.i4.3 ldc.i4 0xc add sub.ovf.un pop Branch_0x1: ldc.i4 0x8e9bf46e ret } .method static int32 Main() { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 20 .try { call int32 ILGEN_0x493230e7::Method_0x2d7c921() pop leave END } catch [mscorlib]System.OverflowException { pop leave END } END: ldc.i4 100 ret } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern legacy library mscorlib {} .assembly extern System.Console { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) .ver 4:0:0:0 } .assembly 'b58358' {} .assembly extern xunit.core {} .class ILGEN_0x493230e7 { .method static int32 Method_0x2d7c921() { .maxstack 11 ldc.r4 float32(0x6ef1549c) call float64 [mscorlib]System.Math::Sin(float64) ldc.r8 4.4 bgt Branch_0x2 ldc.i4 0xe br Branch_0x3 Branch_0x2: ldc.i4.6 Branch_0x3: ldc.i4.8 ble.un Branch_0x0 br Branch_0x1 Branch_0x0: ldc.i4.8 ldc.i4.3 ldc.i4 0xc add sub.ovf.un pop Branch_0x1: ldc.i4 0x8e9bf46e ret } .method static int32 Main() { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 20 .try { call int32 ILGEN_0x493230e7::Method_0x2d7c921() pop leave END } catch [mscorlib]System.OverflowException { pop leave END } END: ldc.i4 100 ret } }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/libraries/System.Reflection.Metadata/tests/Resources/PortablePdbs/Documents.Embedded.dll
MZ@ !L!This program cannot be run in DOS mode. $PEL-_" 0:& @ @%O@` #T  H.text@  `.rsrc@ @@.reloc `@B&H 0c( ( ( ( ( ( ( ( ( ( ( ( ( ( *"( *BSJB v4.0.30319l#~l#Stringsh#USl#GUID|T#BlobG 3Pp<* P    1212). ".+.J<Module>CMmscorlibDocuments.EmbeddedConsoleWriteLineDebuggableAttributeCompilationRelaxationsAttributeRuntimeCompatibilityAttributeDocuments.Embedded.dllSystem.ctorSystem.DiagnosticsSystem.Runtime.CompilerServicesDebuggingModesObjectVE-B*\'   z\V4TWrapNonExceptionThrows RMP/#$RSDS'VF?KDocuments.Embedded.pdbMPDBs rbd`d pqR(33 01I VHI- ~CP \R^ /3T { SN>ȰN涵?~> 3E84# LP b3C!.CP^zF(- dYPP:J@2(] [D(Jۡ>KY@6,Lbd`@o$ǭml#)e 3-d` ,.IebddrqO.M+)K.fZZ7A'J5c"cc2c !P{ b FXET 3:pY\("0ۢQ5jjer~ Y& P 02012q003LA V6(DBq@(N!⅚T&(& &_CorDllMainmscoree.dll% 0HX@tt4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0NInternalNameDocuments.Embedded.dll(LegalCopyright VOriginalFilenameDocuments.Embedded.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 <6
MZ@ !L!This program cannot be run in DOS mode. $PEL-_" 0:& @ @%O@` #T  H.text@  `.rsrc@ @@.reloc `@B&H 0c( ( ( ( ( ( ( ( ( ( ( ( ( ( *"( *BSJB v4.0.30319l#~l#Stringsh#USl#GUID|T#BlobG 3Pp<* P    1212). ".+.J<Module>CMmscorlibDocuments.EmbeddedConsoleWriteLineDebuggableAttributeCompilationRelaxationsAttributeRuntimeCompatibilityAttributeDocuments.Embedded.dllSystem.ctorSystem.DiagnosticsSystem.Runtime.CompilerServicesDebuggingModesObjectVE-B*\'   z\V4TWrapNonExceptionThrows RMP/#$RSDS'VF?KDocuments.Embedded.pdbMPDBs rbd`d pqR(33 01I VHI- ~CP \R^ /3T { SN>ȰN涵?~> 3E84# LP b3C!.CP^zF(- dYPP:J@2(] [D(Jۡ>KY@6,Lbd`@o$ǭml#)e 3-d` ,.IebddrqO.M+)K.fZZ7A'J5c"cc2c !P{ b FXET 3:pY\("0ۢQ5jjer~ Y& P 02012q003LA V6(DBq@(N!⅚T&(& &_CorDllMainmscoree.dll% 0HX@tt4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0NInternalNameDocuments.Embedded.dll(LegalCopyright VOriginalFilenameDocuments.Embedded.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 <6
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/IServiceProviderFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// Provides an extension point for creating a container specific builder and an <see cref="IServiceProvider"/>. /// </summary> public interface IServiceProviderFactory<TContainerBuilder> where TContainerBuilder : notnull { /// <summary> /// Creates a container builder from an <see cref="IServiceCollection"/>. /// </summary> /// <param name="services">The collection of services</param> /// <returns>A container builder that can be used to create an <see cref="IServiceProvider"/>.</returns> TContainerBuilder CreateBuilder(IServiceCollection services); /// <summary> /// Creates an <see cref="IServiceProvider"/> from the container builder. /// </summary> /// <param name="containerBuilder">The container builder</param> /// <returns>An <see cref="IServiceProvider"/></returns> IServiceProvider CreateServiceProvider(TContainerBuilder containerBuilder); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// Provides an extension point for creating a container specific builder and an <see cref="IServiceProvider"/>. /// </summary> public interface IServiceProviderFactory<TContainerBuilder> where TContainerBuilder : notnull { /// <summary> /// Creates a container builder from an <see cref="IServiceCollection"/>. /// </summary> /// <param name="services">The collection of services</param> /// <returns>A container builder that can be used to create an <see cref="IServiceProvider"/>.</returns> TContainerBuilder CreateBuilder(IServiceCollection services); /// <summary> /// Creates an <see cref="IServiceProvider"/> from the container builder. /// </summary> /// <param name="containerBuilder">The container builder</param> /// <returns>An <see cref="IServiceProvider"/></returns> IServiceProvider CreateServiceProvider(TContainerBuilder containerBuilder); } }
-1
dotnet/runtime
66,211
[mono] Remove SkipVerification support from the runtime
CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
akoeplinger
2022-03-04T19:47:04Z
2022-03-06T13:44:33Z
b463b1630dbf1be5b013208a9fa73e1ecd6c774c
be629f49a350d526de2c65981294734cee420b90
[mono] Remove SkipVerification support from the runtime. CAS support was removed in .NET Core. This allows us removing a bunch of code that is unused, e.g. the dependency on libiconv.
./src/coreclr/jit/opcode.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XX XX opcodes.h XX XX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ /*****************************************************************************/ #ifndef _OPCODE_H_ #define _OPCODE_H_ #include "openum.h" extern const signed char opcodeSizes[]; #if defined(DEBUG) extern const char* const opcodeNames[]; extern const BYTE opcodeArgKinds[]; #endif /*****************************************************************************/ #endif // _OPCODE_H_ /*****************************************************************************/
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XX XX opcodes.h XX XX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ /*****************************************************************************/ #ifndef _OPCODE_H_ #define _OPCODE_H_ #include "openum.h" extern const signed char opcodeSizes[]; #if defined(DEBUG) extern const char* const opcodeNames[]; extern const BYTE opcodeArgKinds[]; #endif /*****************************************************************************/ #endif // _OPCODE_H_ /*****************************************************************************/
-1